3
votes

The java documentation says that it's mandatory for a checked exception to specify an handler that can "catch" the exception or to throws it in the method declaration. But, if i do, for example:

public class DivZero{
 public static void main(String[] args){
   int a=10;
   int[] b={1,2,3,4,0};
   for (int i=0;i<b.length;i++){
    System.out.println(a/b[i]);
   }
 }
}

It works fine also without "try-catch" or "throws" declaration. It throws a java.lang.ArithmeticException. So, it's not mandatory? The compiler implicitly throws the suitable Java "Throwable" class in the same way. It's so?

4

4 Answers

5
votes

ArithmeticException extends RuntimeException thus it is not a checked exception. Checked exceptions are the ones inheriting from Exception but not from RuntimeException.

Quoting JLS, 11.1.1. The Kinds of Exceptions:

[...] checked exception classes are all subclasses of Throwable other than RuntimeException and its subclasses and Error and its subclasses.

2
votes

You have to catch only checked exceptions: sublcasses of java.lang.Exception that are not subclasses of java.lang.RuntimeException. ArithmeticException is a sublcass of RuntimeException.

RuntimeException(s) usually signal bugs in your application, so you have to solve them, not to catch the exceptions. In your case ArithmeticException is thrown at line System.out.println(a/b[i]); because you are trying to divide an int by 0. You need to make sure that such divisions doesn't happen in your program.

2
votes

There are two kinds of exceptions in Java: the ones that extend Exception are called checked and need to be handled (catching them, or throwing them) - for example, IOException. The ones that extend from RuntimeException are called unchecked and don't need to be handled explicitly, unless you need to do something with them - for example, NullPointerException.

For the code in the question, you can see that ArithmeticException extends from RuntimeException, therefore is unchecked and you don't need to explicitly handle it.

1
votes

ArithmeticException is not a checked exception, thats why it allows you to compile fine. Child classes of Exception are called checked exceptions remaining all are unchecked.