Java的try-catch-finally

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

 

Javac语法糖之TryCatchFinally

 

如下引用文章:https://help.semmle.com/wiki/display/JAVA/Finally+block+may+not+complete+normally

 

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: 

  • return
  • throw
  • break
  • continue

举例子:

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的执行流程图如下:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/extjs4/p/9375400.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值