一直有一个疑惑: 在某个Java项目中究竟需要使用检查型Exception还是非检查型Exception(RuntimeException), 例如有时我们需要定义一个全局型的Exception, 举个例子, 假设项目名称是Abc, 我们需要定义一个AbcException用于全局的异常处理. 应该是定义成RuntimeException(非检查型)还是普通的检查型Exception(直接继承Exception). 刚才看了以下这篇文章(http://tutorials.jenkov.com/java-exception-handling/checked-or-unchecked-exceptions.html), 我感觉清楚多了. 后面是是文章是最后结论, 作者大致意思是原先他倾向检查型, 但现在他的想法发生了转变: 倾向使用非检查型Exception.
原因是: 可能节省大量的try-catch代码, 或一层层向上throw, 方面集中进行错误处理, 可读性提高.
Summary
I used to be in favor of checked exceptions but recently I have begun to change my mind. Personalities like Rod Johnson (Spring Framework), Anders Hejlsberg (father of C#), Joshua Bloch (Effective Java, item 41: Avoid unnecessary use of checked exceptions) and others have made me rethink the real benefit of checked exceptions. Lately we have tried using unchecked exceptions on a larger project, and they have worked out just fine. The error handling is centralized in a few classes. Here and there we have had to do local error handling instead of propagating the exception to the main error handling code. But it is not in very many places. Our code has become somewhat more readable now that there aren't try-catch blocks all over the code. In other words, there are a lot less no-benefit catch-rethrow try-catch blocks in the code than with checked exceptions. All in all I would recommend using unchecked exceptions. At least give it a try on a project. I have summarized the reasons below:
- Unchecked exceptions do not clutter the code with unnecessary try-catch blocks.
- Unchecked exceptions do not clutter the method declarations with aggregated exception declarations.
- The argument that you easier forget to handle unchecked exceptions is not valid in my experience.
- The argument that it is harder to know how to handle undeclared exceptions is not valid in my experience.
- Unchecked exceptions avoids versioning problems altogether.
You or your project will have to make your own decisions about whether to use checked or unchecked exceptions, or both. Here is a list of resources that also discusses the decision between checked and unchecked exceptions.