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();
}
}
public class MyClass { public static void method() { try { // there is
Share
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.