Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: catching specific Exceptions

Tags:

java

say I have the following

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

What would happen when it comes across SpecificException ? Does it catch it as a generic exception first, and then catch the specificexception ?

Or does it only catch SpecificException while ignoring generic exceptions.

I don't want both generic and specificexception being caught.

like image 786
heysup Avatar asked Dec 30 '10 21:12

heysup


2 Answers

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
}
like image 86
duffymo Avatar answered Oct 26 '22 16:10

duffymo


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.

like image 25
Michael Borgwardt Avatar answered Oct 26 '22 16:10

Michael Borgwardt