findbugs異常(1):Exception is caught when Exception is not thrown
阿新 • • 發佈:2019-02-17
Exception is caught when Exception is not thrown 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. A better approach is to either explicitly catch the specific exceptions that are thrown, or to explicitly catch RuntimeException exception, rethrow it, and then catch all non-Runtime Exceptions, as shown below: try { ... } catch (RuntimeException e) { throw e; } catch (Exception e) { ... deal with all non-runtime exceptions ... } |
2. 一般人都會這樣寫程式碼:
try{
//
}
catch(Exception ex){
//
}
3. 這樣很省事,但是JAVA規範中並不推薦這樣做,這樣是屬於“過泛地捕獲異常”,因為try{}中可能出現的異常種類有很多,上面的做法不利於分別處理各種異常,建議根據業務需求,分別捕獲需要特別處理的異常,例子如下: try{
//
}
catch(SQLException ex){
//
}
catch(IOException ex){
//
}
catch(Exception ex){
//
}
4. 捕獲的異常一定要丟擲,並列印日誌。