| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Java FAQ:
What can you catch when try block does not throw exception?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
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:
|