cj612 cj612 - 2 months ago 8
Java Question

Java - Catch all other unanticipated exceptions

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
?

Thanks

Answer

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

Comments