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

来源:互联网 发布:ipad淘宝旧版本下载 编辑:程序博客网 时间:2024/06/05 16:55
REC_CATCH_EXCEPTION




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


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.比较推荐的写法一般如下:
Java代码  收藏代码
  1. try {  
  2. }catch(IOException e){  
  3.   
  4. }finally{  
  5. }  

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

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




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





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.
原创粉丝点击