需要权威的原因为什么你不应该抛出或者捕获java.lang.Exception [英] Need authoritative source for why you shouldn't throw or catch java.lang.Exception

查看:358
本文介绍了需要权威的原因为什么你不应该抛出或者捕获java.lang.Exception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在短短一个多小时内就有了一个编码标准会议,我需要一个快速的回答。



经验丰富的Java程序员之间的共同智慧就是你不要抛出或者捕获java.lang.Exception(除了少数例外 - 没有双关语)。你不这样做的原因是语句

  catch(java.lang.Exception ex){...} 

还将捕获未经检查的异常,在大多数情况下,这不是预期的。



我们已经有很多现有团队成员编写的遗留代码,它们捕获java.lang.Exception的子类,记录错误,并将子类重新推送为java.lang.Exception



我需要说服他们


  1. 他们需要停止写代码

  2. 使用此反花样的现有代码需要修复

数字2意味着大量的重构。



如果我可以显示一个Java社区重量级的一个文章或博客条目,会议会缩短参数, (即约书亚布洛赫,詹姆斯·戈斯林)。有没有人知道某个文章或博客受到尊敬的Java大师,他说你不应该扔或者捕获java.lang.Exception?



快速回答非常感激。



Dean

解决方案

这里有一些:(JavaWorld)



有效的Java (第二版)作者Joshua Bloch可能会在第9章(例外)中有所提及,虽然我不能t快速找到关于不捕捉的东西异常



这里是 JavaWorld的Q& A,关于问题(也指Java Tip 134) - 它也解释了为什么你有时必须打破不捕捉的规则异常甚至 Throwable


I've got a coding standards meeting in just over an hour and I need a quick answer to this one.

Common wisdom among experienced Java programmers is that you don't throw or catch java.lang.Exception (with rare exceptions - no pun intended). The reason you don't do this is that the statement

catch (java.lang.Exception ex) {...}

will also catch unchecked Exceptions, and in most cases this is not what is intended.

We already have a lot of legacy code written by existing team members where they catch a subclass of java.lang.Exception, log an error, and rethrow the subclass as java.lang.Exception.

I need to convince them that

  1. They need to stop writing code like this.
  2. Existing code that uses this anti-pattern needs to be fixed

Number 2 means a fair amount of refactoring.

It will shorten the argument at the meeting if I can show an article or blog entry by one of the Java community heavyweights that makes this point (i.e. Joshua Bloch, James Gosling). My google-fu hasn't turned up anything so far.

Does anyone know of an article or blog by a respected Java guru that says that you shouldn't throw or catch java.lang.Exception?

Quick answers are much appreciated.

Dean

解决方案

Here's something: Java Tip 134: When catching exceptions, don't cast your net too wide (JavaWorld)

Effective Java (Second Edition) by Joshua Bloch might have something on this in Chapter 9 (Exceptions), although I couldn't quickly find anything about not catching Exception.

Here is a Q&A from JavaWorld about the question (also points to Java Tip 134) - it also explains why you sometimes have to break the rule of not catching Exception or even Throwable.

这篇关于需要权威的原因为什么你不应该抛出或者捕获java.lang.Exception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆