Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "throws ArithmeticException" only cosmetic in the method definiton?

Tags:

java

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");
    }
}
like image 440
Zoltan King Avatar asked Mar 03 '23 03:03

Zoltan King


1 Answers

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.

like image 200
Joseph Sible-Reinstate Monica Avatar answered May 21 '23 17:05

Joseph Sible-Reinstate Monica