究竟需要使用检查型Exception还是非检查型Exception(RuntimeException)

一直有一个疑惑: 在某个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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值