Java: catching specific Exceptions

The catch blocks are tried in order, and the first one that matches the type of the exception is executed. Since Exception is the superclass of all exception types, it will always be executed in this instance and the specific cases will never be executed. In fact the compiler is smart enough to notice this and raise a compilation error.

Just reorder the catch clauses.


This does not compile with eclipse compiler:

Unreachable catch block for IOException. It is already handled by the catch block for Exception

So define them the other way. Only the specific one will be caught.


This won't compile. You'll be told that the specific exception block isn't reachable.

You have to have the more specific exception catch block first, followed by the general one.

try
{
    //something
} 
catch(SpecificException se)
{
    //catch specific exception only
}
catch(Exception generic)
{
    //catch all
}

No. All exceptions would be caught by the first block. The second will never be reached (which the compiler recognizes, leading to an error due to unreachable code). If you want to treat SpecificException specifically, you have to do it the other way round:

}catch(SpecificException se){
//catch specific exception only
}catch(Exception generic){
//catch all
}

Then SpecificException will be caught by the first block, and all others by the second.

Tags:

Java