Domanda

I am new at Java and am experiencing a bit of a problem with throwing exceptions. Namely, why is this incorrect

public static void divide(double x, double y){
    if(y == 0){
    throw new Exception("Cannot divide by zero."); 
        //Generates error message that states the exception type is unhanded 
}
else
    System.out.println(x + " divided by " + y + " is " + x/y);
    //other code follows
}

But this ok?

public static void divide(double x, double y){
if(y == 0)
    throw new ArithmeticException("Cannot divide by zero.");
else
    System.out.println(x + " divided by " + y + " is " + x/y);
    //other code follows
}
È stato utile?

Soluzione

An ArithmeticException is a RuntimeException, so it doesn't need to be declared in a throws clause or caught by a catch block. But Exception isn't a RuntimeException.

Section 11.2 of the JLS covers this:

The unchecked exception classes (§11.1.1) are exempted from compile-time checking.

The "unchecked exception classes" include Errors and RuntimeExceptions.

Additionally, you'll want to check if y is 0, not if x / y is 0.

Altri suggerimenti

You need to add a throws in the method signature only for unchecked exceptions.For example:

public static void divide(double x, double y) throws Exception {
 ...
}

Since ArithmeticException extends RuntimeException, there's no need of a throws in the second example.

More info:

Methods that throw exceptions in Java must delcare it in the method signature

public static void divide(double x, double y) throws Exception

Without the declaration your code will not compile.

There is a special subset of exceptions that extend the RuntimeException class. These exceptions do not need to be declared in the method signature.

ArithmeticException extends a RuntimeException

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top