Why does the following code compile fine, but the method being called does not need to throw Exception
? Isn't Exception
a checked exception and not an unchecked exception? Please clarify.
class App {
public static void main(String[] args) {
try {
amethod();
System.out.println("try ");
} catch (Exception e) {
System.out.print("catch ");
} finally {
System.out.print("finally ");
}
System.out.print("out ");
}
public static void amethod() { }
}
If I want to use a try catch with IOexception
(a checked exception), the method being called needs to throw IOException
. I get this.
import java.io.IOException;
class App {
public static void main(String[] args) {
try {
amethod();
System.out.println("try ");
} catch (IOException e) {
System.out.print("catch ");
} finally {
System.out.print("finally ");
}
System.out.print("out ");
}
public static void amethod() throws IOException { }
}
Isn't 'Exception' a checked exception and not an unchecked exception?
Yes, it is.
But even if we know the method doesn't throw Exception
itself, the code catch(Exception e){
could still execute. The code in the try
block could still throw something that inherits from Exception
. That includes RuntimeException
and its subclasses, which are unchecked.
catch(IOException e){
, on the other hand, can only catch checked exceptions. (Java doesn't allow multiple inheritance, so anything that's a subclass of IOException
can't possibly be a subclass of RuntimeException
.) The compiler can fairly easily figure out that none of the code in the try
block can possibly throw an IOException
(since any method throwing a checked exception must explicitly say so) which allows it to flag the code.
The behavior you're observing comes from the fact that the Java Language Specification treats Exception
specially in this circumstance. According to §11.2.3 :
It is a compile-time error if a catch clause can catch checked exception class E 1 and it is not the case that the
try
block corresponding to thecatch
clause can throw a checked exception class that is a subclass or superclass of E 1 , unless E 1 isException
or a superclass ofException
.
This is reasonable because Exception
(and its superclass Throwable
) can be used to catch exceptions that extend RuntimeException
also. Since runtime exceptions are always possible, the compiler always allows Exception
to appear in a catch
clause regardless of the presence of checked exceptions.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.