I decided to remove the throws ArithmeticException in the code below and I still got the same result when I divided by zero and the stack trace appeared. Is throws ArithmeticException in the method definition optional? What is its purpose?
public static int quotient(int numerator, int denominator) throws ArithmeticException {
return numerator / denominator;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
int denominator = scanner.nextInt();
System.out.println(quotient(10, denominator));
} catch(ArithmeticException e) {
System.out.println("Aritmetic exception");
} catch(InputMismatchException e) {
System.out.println("InputMismatchException");
}
}
ArithmeticException is a subclass of RuntimeException, and unlike most exceptions, RuntimeExceptions are unchecked and so don't need to be declared in throws declarations. So yes, it's unnecessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With