Reputation: 2983
Is it good practice to append a general exception catch when handling exceptions. an example may make this question clearer
try{
// do something
}catch(spomespecificException1 ex){
//logging and other stuff
}catch(spomespecificException2 ex){
//logging and other stuff
}catch(Exception ex){
//logging and other stuff
}
should i append the exception catch to the stack
Upvotes: 4
Views: 160
Reputation: 401
Exceptions do generally happen especially if your accessing something outside your application like connection errors etc.
If you want to filter out the type of exceptions and do something different for each particular type, then there's nothing wrong with doing this.
A better coding practice would be preventing these exceptions from happening in the first place.
Upvotes: 0
Reputation: 48455
The code you have posted is fine if you want to do some specific handling relating to that exception - which you would want to do in one of the other catch blocks. A good example might be when you are trying to connect to an SQL database and you can handle the different error messages in different ways.
Also, remember there is a "finally" block you can add to the end to do all clean up (and common) handling code, but you will not get exception information in there
Upvotes: 1
Reputation: 161831
You shouldn't be catching those exceptions at all, in general. Don't catch exceptions that you don't actually know how to handle.
"Handle" means fix. If you can't fix the problem, or if you can't add additional information, then don't catch the exception.
Upvotes: 7
Reputation: 88092
It depends on the situation and how far up the stack you want to let an exception bubble before being caught.
There are certainly reasons for and against but without details specific to your situation it's impossible to tell.
So, is there a general "rule" about it? no.
Upvotes: 4