public class MyClass {
public static void method() {
try {
// there is no compile time error for unnecessary catching 'Exception'
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
// why compile time error for unnecessary catching 'MyException' or
// 'CloneNotSupportedException' etc..
// ultimately Exception, MyException & CloneNotSupportedException all
// are checked exception
} catch (MyException e) {
e.printStackTrace();
}
}
}
class MyException extends Exception {
}
second scenario
---------------
public class MyClass {
public static void method() throws Exception {
}
public static void main(String[] args) {
// if Exception itself is not checked ,
// why compile time error occured for calling method(); ??
method();
开发者_Python百科 }
}
Because RuntimeExceptions are subclasses of Exception class. Therefore, compiler can't determine if some code throws any runtime exception, as they might be thrown by jvm. On the other hand - checked exceptions must be declared that are thrown by some method, so the compiler knows which exceptions could be thrown and can determine unnecessary catch blocks.
Methods declare what exceptions they throw. If you're catching anything that is not a superclass of any known exception types then the catching isn't necessary.
We have checked exceptions and unchecked Exceptions. CloneNotSupportedException
is a checked exception: if a methods throws it, the caller needs to catch this type of exception. And in those cases, the jvm can detect, if it is catched while no method inside the try block ever throws it.
Exception
itself is not checked.
精彩评论