I have been reading many posts about exceptions lately and I have a question whether unchecked exceptions should be caught. I have read that if you want your application to recover from an error you use checked exceptions. However if you can't deal with the checked exception you either wrap it into another checked exception so you can pass it to another layer; for instance you wrap an SqlException
, or you throw an unchecked exception. However, should you catch unchecked exceptions? Are unchecked exceptions ideally programming errors that you don't check for? Should they just bubble up from your application?
Should unchecked exceptions be caught and dealt with?
The answer is that it depends:
It depends on what the exception is.
It depends on why the exception was thrown. Was it "expected"? Was it due to a bug, or bad input, or an environmental problem? Or something else?
It depends if there is a good way to recover. That typically depends in part on the previous criteria.
If the exception is unexpected, the cause of the exception is uncertain, and / or if there is no sound recovery strategy if you do catch the exception, then it is generally better to allow the exception to bubble up, and make sure that it gets reported / logged at the top level.
And if the exception is an Error
, the general rule is that you should NOT attempt to recover. And that includes StackOverflowError
and (particularly) OutOfMemoryError
. The Error
exceptions indicate a problem that is difficult (or impossible) to safely recover from, and the best strategy is to allow or cause the application to exit.
What do you mean by reported/logged at the top level? Do you mean catching it at the UI layer for instance and show an dialog, log it etc?
I mean that the exception and its stack trace should be written to the application's log file so that the evidence of the problem is available for the maintainers to look at. Whether you also try to explain the problem to the end user (and how you do that) is a separate issue.
The "top level" may be the "main" method, a child thread or runnable's "run" method ... or an uncaught exception handler. Basically it is wherever the exception eventually will "bubble up" to if it is not caught. Details will depend on your application's architecture.