What can you catch when try block does not throw exception?

Let's take a look at the following code:

class Program {

public static void main(String[] args) {

try {
method();
}
catch (FileNotFoundException e) {
;
}
}

static void method() {
}
}

The above code will generate a compile-time error: "Unreachable catch block ....".

But the following code does not generate a compile time error:

class Program {

public static void main(String[] args) {

try {
method();
}
catch (Exception e) {
;
}
}

static void method() {
}
}

The Java compiler does not require you to catch an unchecked exception. If you do catch an unchecked exception even the code does not throwing it, the compiler will not generate a compile-time error. The unchecked exceptions have the benefit of not forcing the client code to explicitly deal with them.

The RuntimeException and its subclasses are unchecked exceptions. Error and its subclasses are also unchecked exceptions. The RuntimeException is the subclass of Exception, Therefore, catching the Exception exception without throwing any exceptions in try block will not generate comiple-time error.

Summary for try-catch without throw exception:

* Catching Throwable, Error (including its subclasses), Exception, and RuntimeException (including its subclasses) always compile.
* Catching directly subclasses of Throwable except for Exception and Error will generate a compile time error.
* Catching subclasses of Exception except for RuntimeException will generate a compile time error.

No comments:

Post a Comment