简体   繁体   中英

Why Exception class behaves like unchecked exception and does not require try block to throw any checked or even any exceptions at all?

Exception is a checked exception. Why I can write catch (Exception e) when respective try block does not throw anything? This trick is not allowed with any other checked exception like IOException. Some books say that Throwable also shall be considered a checked exception, but it behaves just like Exception.

void f() {
        try {

        } catch (Exception e) {   // fine!


        }
    }


void f() {
        try {

        } catch (Throwable e) {   // also fine!


        }
    }

PS Found this in JLS :

It is a compile-time error if a catch clause can catch checked exception class E1 and it is not the case that the try block corresponding to the catch clause can throw a checked exception class that is a subclass or superclass of E1, unless E1 is Exception or a superclass of Exception.

If you look into the code for Exception , you'll find that it extends Throwable:

public class Exception extends Throwable

Anything that can be throw n is a Throwable . Though this gives a level of flexibility since you can create a custom class that extends throwable (and throw that too). Exception is pretty much just a minimalistic wrapper around Throwable. So essentially:

try{
    //something here that goes wrong causing:
    throw new Exception("Thrown");
}catch(Throwable e){
    System.out.println("Caught");
}

Though catching an Exception will also work. But if you create a new class that extends Throwable, catching Exception will have no effect.

Which means, if you can catch an Exception as a general statement, you can also catch its superclass, being Throwable. Note that it is not a good practice to do so, but I am mentioning it because it is possible. If you have to catch something general, catch Exception, and not Throwable.

Louis Wasserman's comment is correct. Exception is the super class of RuntimeException. Thus, catching Exception also catches all unchecked 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM