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?
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With