Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when the code throw many exception and the handle is same, which choice is better?

Tags:

java

exception

when the code throw many exception and the handle is same, which choice is better?

try{
}catch(ExceptionOne e1)
{
someHandle()
}
catch(ExceptionTwo e2){
someHandle()
}
catch(ExceptionThree e3)
{
someHandle()
}

or

try{
}catch(Exception e1)
{
someHandle()
}

some books meationed that when encoutering exception, try catch it clearly , not try cacth all exception.

So which is better?

like image 828
jiafu Avatar asked Dec 31 '25 01:12

jiafu


1 Answers

The first is better. The second catches all exceptions, and that might include some exceptions that you do not want to catch.

If you upgrade to Java 7 you could use a catch block that can catch more than one type of exception, which is a cleaner solution.

try {
    // Something that might throw.
}
catch(ExceptionOne | ExceptionTwo | ExceptionThree e) {
    someHandle()
}
like image 182
Mark Byers Avatar answered Jan 02 '26 13:01

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!