简体   繁体   中英

Casting of Exception necessity

Quick question guys, I've see a lot of code regarding try/catch blocks and I've seen it a lot of times, that people use specific Exceptions for stuff. I mean, what kind of reason would you have to do that? I usually just put an Exception e inside the catch block and just read it out from the Log... is it a performance issue or just habit?

Having different exception classes allows you to have specific exception code without having to determine the type.

For example, rather than writing:

try {
   ...do some stuff
} catch( Exception e ) {
    if( e instanceof NullpointerException ) {
        ... do something
    } else if( e instanceof IOExceptio ) {
        ... do something else 
    }
}

you can just write:

try {
    ... do something ...
} catch ( NullpointerException epe ) {
    ... handle NPE
} catch ( IOException ioe ) {
    ... handle IO Exception
}

etc.

Further, you can also choose to catch only some exceptions, and allow others to be thrown by the method:

public void doSomeIO() throws IOException {

    try {
        ... do something ...
    } catch( NullpointerException ) {
        ... handle NPE
    }

}

And then you'd call it:

try {
    doSomeIO();
except ( IOException ) {
    handle the IO exception
}

This way you can have specific exception handling where it belongs, and allow others to bubble up where they can be handled better.

The error is not the same if you catch a ClassCastException than if you catch a ArrayIndexOutOfBounds exceptions. You should handle them accordingly.

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