详谈Java 异常处理的误区和经验总结(分享)

2025-05-29 0 75

本文着重介绍了 java 异常选择和使用中的一些误区,希望各位读者能够熟练掌握异常处理的一些注意点和原则,注意总结和归纳。只有处理好了异常,才能提升开发人员的基本素养,提高系统的健壮性,提升用户体验,提高产品的价值。

误区一、异常的选择

图 1. 异常分类

详谈Java 异常处理的误区和经验总结(分享)

图 1 描述了异常的结构,其实我们都知道异常分检测异常和非检测异常,但是在实际中又混淆了这两种异常的应用。由于非检测异常使用方便,很多开发人员就认为检测异常没什么用处。其实异常的应用情景可以概括为以下:

一、调用代码不能继续执行,需要立即终止。出现这种情况的可能性太多太多,例如服务器连接不上、参数不正确等。这些时候都适用非检测异常,不需要调用代码的显式捕捉和处理,而且代码简洁明了。

二、调用代码需要进一步处理和恢复。假如将 sqlexception 定义为非检测异常,这样操作数据时开发人员理所当然的认为 sqlexception 不需要调用代码的显式捕捉和处理,进而会导致严重的 connection 不关闭、transaction 不回滚、db 中出现脏数据等情况,正因为 sqlexception 定义为检测异常,才会驱使开发人员去显式捕捉,并且在代码产生异常后清理资源。当然清理资源后,可以继续抛出非检测异常,阻止程序的执行。根据观察和理解,检测异常大多可以应用于工具类中。java学习群669823128

误区二、将异常直接显示在页面或客户端。

将异常直接打印在客户端的例子屡见不鲜,以 jsp 为例,一旦代码运行出现异常,默认情况下容器将异常堆栈信息直接打印在页面上。其实从客户角度来说,任何异常都没有实际意义,绝大多数的客户也根本看不懂异常信息,软件开发也要尽量避免将异常直接呈现给用户。

清单 1

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25
<strong>package</strong> com.ibm.dw.sample.exception;

/**

* 自定义 runtimeexception

* 添加错误代码属性

*/

<strong>public</strong> <strong>class</strong> <strong>runtimeexception</strong> <strong>extends</strong> <strong>java</strong>.<strong>lang</strong>.<strong>runtimeexception</strong> {

//默认错误代码

<strong>public</strong> <strong>static</strong> <strong>final</strong> integer generic = 1000000;

//错误代码

<strong>private</strong> integer errorcode;

<strong>public</strong> <strong>runtimeexception</strong>(integer errorcode, throwable cause) {

<strong>this</strong>(errorcode, <strong>null</strong>, cause);

}

<strong>public</strong> <strong>runtimeexception</strong>(string message, throwable cause) {

//利用通用错误代码

<strong>this</strong>(generic, message, cause);

}

<strong>public</strong> <strong>runtimeexception</strong>(integer errorcode, string message, throwable cause) {

<strong>super</strong>(message, cause);

<strong>this</strong>.errorcode = errorcode;

}

<strong>public</strong> integer <strong>geterrorcode</strong>() {

<strong>return</strong> errorcode;

}

}

正如示例代码所示,在异常中引入错误代码,一旦出现异常,我们只要将异常的错误代码呈现给用户,或者将错误代码转换成更通俗易懂的提示。其实这里的错误代码还包含另外一个功能,开发人员亦可以根据错误代码准确的知道了发生了什么类型异常。

误区三、对代码层次结构的污染

我们经常将代码分 service、business logic、dao 等不同的层次结构,dao 层中会包含抛出异常的方法,如清单 2 所示:

清单 2

?

1

2

3
<strong>public</strong> customer <strong>retrievecustomerbyid</strong>(long id) <strong>throw</strong> sqlexception {

//根据 id 查询数据库

}

上面这段代码咋一看没什么问题,但是从设计耦合角度仔细考虑一下,这里的 sqlexception 污染到了上层调用代码,调用层需要显式的利用 try-catch 捕捉,或者向更上层次进一步抛出。根据设计隔离原则,我们可以适当修改成:

清单 3

?

1

2

3

4

5

6

7

8

9

10
<strong>public</strong> customer <strong>retrievecustomerbyid</strong>(long id) {

<strong>try</strong>{

//根据 id 查询数据库

}<strong>catch</strong>(sqlexception e){

//利用非检测异常封装检测异常,降低层次耦合

<strong>throw</strong> <strong>new</strong> runtimeexception(sqlerrorcode, e);

}<strong>finally</strong>{

//关闭连接,清理资源

}

}

误区四、忽略异常

如下异常处理只是将异常输出到控制台,没有任何意义。而且这里出现了异常并没有中断程序,进而调用代码继续执行,导致更多的异常。

清单 4

?

1

2

3

4

5

6

7

8

9

10

11
<strong>public</strong> <strong>void</strong> <strong>retrieveobjectbyid</strong>(long id){

<strong>try</strong>{

//..some code that throws sqlexception

}<strong>catch</strong>(sqlexception ex){

/**

*了解的人都知道,这里的异常打印毫无意义,仅仅是将错误堆栈输出到控制台。

* 而在 production 环境中,需要将错误堆栈输出到日志。

* 而且这里 catch 处理之后程序继续执行,会导致进一步的问题*/

ex.printstacktrace();

}

}

可以重构成:

清单 5

?

1

2

3

4

5

6

7

8

9

10

11
<strong>public</strong> <strong>void</strong> <strong>retrieveobjectbyid</strong>(long id){

<strong>try</strong>{

//..some code that throws sqlexception

}

<strong>catch</strong>(sqlexception ex){

<strong>throw</strong> <strong>new</strong> runtimeexception(“exception <strong>in</strong> retieveobjectbyid”, ex);

}

<strong>finally</strong>{

//clean up resultset, statement, connection etc

}

}

这个误区比较基本,一般情况下都不会犯此低级错误。

误区五、将异常包含在循环语句块中

如下代码所示,异常包含在 for 循环语句块中。

清单 6

?

1

2

3

4

5

6
<strong>for</strong>(<strong>int</strong> i=0; i<100; i++){

<strong>try</strong>{

}<strong>catch</strong>(xxxexception e){

//….

}

}

我们都知道异常处理占用系统资源。一看,大家都认为不会犯这样的错误。换个角度,类 a 中执行了一段循环,循环中调用了 b 类的方法,b 类中被调用的方法却又包含 try-catch 这样的语句块。褪去类的层次结构,代码和上面如出一辙。

误区六、利用 exception 捕捉所有潜在的异常

一段方法执行过程中抛出了几个不同类型的异常,为了代码简洁,利用基类 exception 捕捉所有潜在的异常,如下例所示:

清单 7

?

1

2

3

4

5

6

7

8

9
<strong>public</strong> <strong>void</strong> <strong>retrieveobjectbyid</strong>(long id){

<strong>try</strong>{

//…抛出 ioexception 的代码调用

//…抛出 sqlexception 的代码调用

}<strong>catch</strong>(exception e){

//这里利用基类 exception 捕捉的所有潜在的异常,如果多个层次这样捕捉,会丢失原始异常的有效信息

<strong>throw</strong> <strong>new</strong> runtimeexception(“exception <strong>in</strong> retieveobjectbyid”, e);

}

}

可以重构成

清单 8

?

1

2

3

4

5

6

7

8

9

10

11
<strong>public</strong> <strong>void</strong> <strong>retrieveobjectbyid</strong>(long id){

<strong>try</strong>{

//..some code that throws runtimeexception, ioexception, sqlexception

}<strong>catch</strong>(ioexception e){

//仅仅捕捉 ioexception

<strong>throw</strong> <strong>new</strong> runtimeexception(/*指定这里 ioexception 对应的错误代码*/code,“exception <strong>in</strong> retieveobjectbyid”, e);

}<strong>catch</strong>(sqlexception e){

//仅仅捕捉 sqlexception

<strong>throw</strong> <strong>new</strong> runtimeexception(/*指定这里 sqlexception 对应的错误代码*/code,“exception <strong>in</strong> retieveobjectbyid”, e);

}

}

误区七、多层次封装抛出非检测异常

如果我们一直坚持不同类型的异常一定用不同的捕捉语句,那大部分例子可以绕过这一节了。但是如果仅仅一段代码调用会抛出一种以上的异常时,很多时候没有必要每个不同类型的 exception 写一段 catch 语句,对于开发来说,任何一种异常都足够说明了程序的具体问题。

清单 9

?

1

2

3

4

5

6

7
<strong>try</strong>{

//可能抛出 runtimeexception、ioexeption 或者其它;

//注意这里和误区六的区别,这里是一段代码抛出多种异常。以上是多段代码,各自抛出不同的异常

}<strong>catch</strong>(<strong>exception</strong> e){

//一如既往的将 exception 转换成 runtimeexception,但是这里的 e 其实是 runtimeexception 的实例,已经在前段代码中封装过

<strong>throw</strong> <strong>new</strong> runtimeexception(/**/code, /**/, e);

}

如果我们如上例所示,将所有的 exception 再转换成 runtimeexception,那么当 exception 的类型已经是 runtimeexception 时,我们又做了一次封装。将 runtimeexception 又重新封装了一次,进而丢失了原有的 runtimeexception 携带的有效信息。

解决办法是我们可以在 runtimeexception 类中添加相关的检查,确认参数 throwable 不是 runtimeexception 的实例。如果是,将拷贝相应的属性到新建的实例上。或者用不同的 catch 语句块捕捉 runtimeexception 和其它的 exception。个人偏好方式一,好处不言而喻。

误区八、多层次打印异常

我们先看一下下面的例子,定义了 2 个类 a 和 b。其中 a 类中调用了 b 类的代码,并且 a 类和 b 类中都捕捉打印了异常。

清单 10

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27
<strong>public</strong> <strong>class</strong> <strong>a</strong> {

<strong>private</strong> <strong>static</strong> logger logger = loggerfactory.getlogger(a.class);

<strong>public</strong> <strong>void</strong> <strong>process</strong>(){

<strong>try</strong>{

//实例化 b 类,可以换成其它注入等方式

b b = <strong>new</strong> b();

b.process();

//other code might cause exception

} <strong>catch</strong>(xxxexception e){

//如果 b 类 process 方法抛出异常,异常会在 b 类中被打印,在这里也会被打印,从而会打印 2 次

logger.error(e);

<strong>throw</strong> <strong>new</strong> runtimeexception(/* 错误代码 */ errorcode, /*异常信息*/msg, e);

}

}

}

<strong>public</strong> <strong>class</strong> <strong>b</strong>{

<strong>private</strong> <strong>static</strong> logger logger = loggerfactory.getlogger(b.class);

<strong>public</strong> <strong>void</strong> <strong>process</strong>(){

<strong>try</strong>{

//可能抛出异常的代码

}

<strong>catch</strong>(xxxexception e){

logger.error(e);

<strong>throw</strong> <strong>new</strong> runtimeexception(/* 错误代码 */ errorcode, /*异常信息*/msg, e);

}

}

}

同一段异常会被打印 2 次。如果层次再复杂一点,不去考虑打印日志消耗的系统性能,仅仅在异常日志中去定位异常具体的问题已经够头疼的了。

其实打印日志只需要在代码的最外层捕捉打印就可以了,异常打印也可以写成 aop,织入到框架的最外层。

误区九、异常包含的信息不能充分定位问题

异常不仅要能够让开发人员知道哪里出了问题,更多时候开发人员还需要知道是什么原因导致的问题,我们知道 java .lang.exception 有字符串类型参数的构造方法,这个字符串可以自定义成通俗易懂的提示信息。

简单的自定义信息开发人员只能知道哪里出现了异常,但是很多的情况下,开发人员更需要知道是什么参数导致了这样的异常。这个时候我们就需要将方法调用的参数信息追加到自定义信息中。下例只列举了一个参数的情况,多个参数的情况下,可以单独写一个工具类组织这样的字符串。

清单 11

?

1

2

3

4

5

6

7

8
public <strong>void</strong> retieveobjectbyid(long id){

<strong>try</strong>{

//..some code that throws sqlexception

}<strong>catch</strong>(sqlexception ex){

//将参数信息添加到异常信息中

<strong>throw</strong> <strong>new</strong> runtimeexception(“exception <strong>in</strong> retieveobjectbyid <strong>with</strong> object id :”+ id, ex);

}

}

误区十、不能预知潜在的异常

在写代码的过程中,由于对调用代码缺乏深层次的了解,不能准确判断是否调用的代码会产生异常,因而忽略处理。在产生了 production bug 之后才想起来应该在某段代码处添加异常补捉,甚至不能准确指出出现异常的原因。这就需要开发人员不仅知道自己在做什么,而且要去尽可能的知道别人做了什么,可能会导致什么结果,从全局去考虑整个应用程序的处理过程。这些思想会影响我们对代码的编写和处理。

误区十一、混用多种第三方日志库

现如今 java 第三方日志库的种类越来越多,一个大项目中会引入各种各样的框架,而这些框架又会依赖不同的日志库的实现。最麻烦的问题倒不是引入所有需要的这些日志库,问题在于引入的这些日志库之间本身不兼容。如果在项目初期可能还好解决,可以把所有代码中的日志库根据需要重新引入一遍,或者换一套框架。但这样的成本不是每个项目都承受的起的,而且越是随着项目的进行,这种风险就越大。

怎么样才能有效的避免类似的问题发生呢,现在的大多数框架已经考虑到了类似的问题,可以通过配置 properties 或 xml 文件、参数或者运行时扫描 lib 库中的日志实现类,真正在应用程序运行时才确定具体应用哪个特定的日志库。

其实根据不需要多层次打印日志那条原则,我们就可以简化很多原本调用日志打印代码的类。很多情况下,我们可以利用拦截器或者过滤器实现日志的打印,降低代码维护、迁移的成本。

结束语

以上纯属个人的经验和总结,事物都是辩证的,没有绝对的原则,适合自己的才是最有效的原则。希望以上的讲解和分析可以对您有所帮助。

原文链接:http://blog.csdn.net/garfielder007/article/details/52141737

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 详谈Java 异常处理的误区和经验总结(分享) https://www.kuaiidc.com/113012.html

相关文章

发表评论
暂无评论