...
Additionally, unchecked exceptions under RuntimeException
are also unintentionally caught when the top level Exception
class is caught.
Code Block | ||
---|---|---|
| ||
import java.io.IOException;
public class DivideException {
public static void main(String[] args) {
try {
division(200,5);
division(200,0); //divide by zero
} catch (Exception e) { System.out.println("Divide by zero exception : " + e.getMessage()); }
}
public static void division(int totalSum, int totalNumber) throws ArithmeticException, IOException {
int average = totalSum/totalNumber;
System.out.println("Average: "+ average);
}
}
|
...
To be compliant, catching specific exception types is advisable especially when the types differ significantly. Here, Arithmetic Exception
and IOException
have been unbundled as they belong to very diverse categories.
Code Block | ||
---|---|---|
| ||
import java.io.IOException;
public class DivideException {
public static void main(String[] args) {
try {
division(200,5);
division(200,0); //divide by zero
} catch (ArithmeticException ae) { System.out.println("Divide by zero exception : " + ae.getMessage()); }
catch (IOException ie) { System.out.println("I/O Exception occurred :" + ie.getMessage()); }
}
public static void division(int totalSum, int totalNumber) throws ArithmeticException, IOException {
int average = totalSum/totalNumber;
System.out.println("Average: "+ average);
}
}
|
...