[M D REC] Exception is caught when Exception is not thrown [REC_CATCH_EXCEPTION]

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.

 

  1.一般人都会这样写代码:

  try{
    //
[hyddd的FindBugs分析记录][M D REC] Exception is caught when Exception is not thrown
  }
  catch(Exception ex){

    
//[hyddd的FindBugs分析记录][M D REC] Exception is caught when Exception is not thrown
  }
这样很省事,但是JAVA规范中并不推荐这样做,这样是属于“过泛地捕获异常”,因为try{}中可能出现的异常种类有很多,上面的做法不利于分别处理各种异常,建议根据业务需求,分别捕获需要特别处理的异常,例子如下:

  try{
    //[hyddd的FindBugs分析记录][M D REC] Exception is caught when Exception is not thrown
  }
  catch(SQLException ex){
    //[hyddd的FindBugs分析记录][M D REC] Exception is caught when Exception is not thrown
  }
  catch(IOException ex){
    //[hyddd的FindBugs分析记录][M D REC] Exception is caught when Exception is not thrown
  }
  catch(Exception ex){
    //[hyddd的FindBugs分析记录][M D REC] Exception is caught when Exception is not thrown
  }
2.另外一个是,捕获到的Exception应尽量记录到LOG文件里。

相关文章: