Reputation: 489
I have several exception types that I am defining and catching (i.e. Network errors, validation error, etc) -- now I basically want to say "Catch all other exceptions that I didn't anticipate."
What is the best way to do this?
Is it just using the generic Excepion e
?
Upvotes: 1
Views: 3932
Reputation: 35096
For best practice, exceptions that do not extend RuntimeException should either be caught and handled, or thrown. There is also setUncaughtExceptionHandler, which can be set in java.lang.Thread
which you can use as a 'catch-all'
Upvotes: -1
Reputation: 140573
Exception is the "largest" type of Exception that one should reasonably catch; as it covers anything that is not an Error.
But a word of warning: depending on your concrete context, catching Exception can still be bad practice. Doing that is typically an indication for one of two things:
And for both options; that is something to avoid!
In other words: catching Exception is something that you normally only do on a very high level - lower levels in your application should exactly know which exceptions come out of lower levels; and only catch those. If at all, you really only want to have one catch (on the "far outside") for Exception. Because: the only thing that you can do in the catch block there - some logging, and an error message to the user.
Upvotes: 1
Reputation: 3927
I would recommend to write all anticipated exceptions and then follow it up with Exception, for e.g.
try
{
}
catch (expectedException1 e)
{
}
.
.
.
catch (Exception e)
{
}
This would help you in taking action over individual exceptions that you are expecting and finally, when you get the Exception, you can handle it generically. Since, Exception class sits at the top of all exceptions, this needs to be at the last. The general rule is, as you go down the list, the hierarchy goes towards top
Upvotes: 8