如下引用文章:https://help.semmle.com/wiki/display/JAVA/Finally+block+may+not+complete+normally
A finally block that does not complete normally suppresses any exceptions that may have been thrown in the corresponding try block. This can happen if the finally block contains any return or throw statements, or if it contains any break or continue statements whose jump target lies outside of the finally block.
Recommendation
To avoid suppressing exceptions that are thrown in a try block, design the code so that the corresponding finally block always completes normally. Remove any of the following statements that may cause it to terminate abnormally:
returnthrowbreakcontinue
举例子:
try {}
catch (Exception e) {}
finally {
throw new Exception() ;
}
try {}
catch (Exception e) {}
finally {
return;
}
L:
try {}
catch (Exception e) {}
finally {
break L;
}
try {}
catch (Exception e) {}
finally {
try{
throw new Exception() ;
}catch(Exception e){
}finally{
return;
}
}
都会出现警告信息finally block does not complete normally,如下则不会:
try {}
catch (Exception e) {}
finally {
try {
throw new Exception();
} catch (Exception e) {
}
}
try {}
catch (Exception e) {}
finally {
L: {
break L;
}
}
关于try-catch-finally的执行流程图如下:

本文深入解析Java中Try-Catch-Finally语句的执行流程及注意事项,强调finally块中不应包含return、throw、break或continue语句,避免异常被抑制。通过具体示例说明如何正确使用finally块,确保异常正常抛出。

被折叠的 条评论
为什么被折叠?



