lmo523
lmo523

Reputation: 489

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?

Upvotes: 1

Views: 3932

Answers (3)

ControlAltDel
ControlAltDel

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

GhostCat
GhostCat

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:

  1. You have no idea what your code is doing
  2. Your code is so complicated that you really can't know what might come out of it

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

prabodhprakash
prabodhprakash

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

Related Questions