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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…