Safe Divide with Exception Handling
Problem
Read two integers a and b. Print a / b as integer division (the result is cut toward zero). If b is 0, print error. Handle the problem with exception handling, not with a hidden check, where the language has exceptions.
Constraints
- |a|, |b| <= 10^9
Examples
Input
10 2
Output
5
Input
5 0
Output
error
Solutions
Java throws ArithmeticException for integer division by zero. Python throws ZeroDivisionError. JavaScript gives Infinity, so we throw our own error.
/*
* Problem : Divide with exceptions.
* Input : Two integers a and b.
* Output : The quotient or error.
* Approach: try / catch.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(long a, long b) {
// Step 1: Try the division. In Java, long division by zero throws ArithmeticException.
try {
return String.valueOf(a / b);
} catch (ArithmeticException exception) {
// Step 2: Catch the problem and return a safe text.
return "error";
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long a = scanner.nextLong();
long b = scanner.nextLong();
System.out.println(solve(a, b));
}
}
Hints (1)
- Which exception does Java throw for 5 / 0?