从 FingBugs的错误来看JAVA代码质量(五)

REC_CATCH_EXCEPTION


[img]http://dl.iteye.com/upload/attachment/0067/9650/0226083e-a04e-35d1-a62c-36bd3321b683.jpg[/img]

[b]Bug: Exception is caught when Exception is not thrown
Pattern id: REC_CATCH_EXCEPTION, type: REC, category: STYLE[/b]

This method uses a try-catch block that catches Exception objects, but Exception is not thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to say try { ... } catch (Exception e) { something } as a shorthand for catching a number of types of exception each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, masking potential bugs.

这想写会无意中把RuntimeException也捕获了,有可能导致潜在的bug。 JVM对RuntimeException有统一的捕获机制,让JVM来处理它。

在try/catch块中捕获异常,但是异常没有在try语句中抛出而RuntimeException又没有明确的被捕获

1.比较推荐的写法一般如下:
try {
}catch(IOException e){

}finally{
}

2.捕获了异常,一定要处理异常
还有人在catch里面什么都不写,就写上

3.避免在大的语句块里面写try,catch,因为本身也比较耗费时间,而且不便于调试和发现问题。


[b]Bug: Call to equals() comparing different types
Pattern id: EC_UNRELATED_TYPES, type: EC, category: CORRECTNESS[/b]


[img]http://dl.iteye.com/upload/attachment/0067/9647/962578df-b808-35e4-9513-ad1cc72927f9.jpg[/img]

This method calls equals(Object) on two references of different class types with no common subclasses. Therefore, the objects being compared are unlikely to be members of the same class at runtime (unless some application classes were not analyzed, or dynamic class loading can occur at runtime). According to the contract of equals(), objects of different classes should always compare as unequal; therefore, according to the contract defined by java.lang.Object.equals(Object), the result of this comparison will always be false at runtime.

两个不同类型的对象调用equals,将永远返回false,除非你重写了equals方法。

调用equals方法比较不同类型的类

This method uses using pointer equality to compare two references that seem to be of different types. The result of this comparison will always be false at runtime.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值