Poor Error Handling: Return Inside Finally

1、摘要

finally块内部返回,这将导致异常丢失,

2、解释

finally块中的return语句将导致丢弃try块中可能引发的任何异常。

3、例子

public static class MagicException extends Exception { }
public static void main(String[] args) {
System.out.println("Watch as this magical code makes an " +
"exception disappear before your very eyes!");
System.out.println("First, the kind of exception handlingyou're used to:");
try {
	doMagic(false);
} catch (MagicException e) {
	// An exception will be caught here
	e.printStackTrace();
}
System.out.println("Now, the magic:");
try {
	doMagic(true);
} catch (MagicException e) {
	// No exception caught here, the finally block ate it
	e.printStackTrace();
}
	System.out.println("tada!");
}
public static void doMagic(boolean returnFromFinally)
throws MagicException {
try {
	throw new MagicException();
}
finally {
	if (returnFromFinally) {
	return;
			}
 		}
 	}
 }

4、建议及提醒

	将return语句移到finally块之外。如果必须返回finally块内部的值,只需
将其赋给一个局部变量,并在finally块执行后返回该值。
	Fortify静态代码分析器将检测显式抛出以及对在finally块中抛出未捕获
异常的方法的调用。
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值