首页  

不要在finally块中使用return     所属分类 java 浏览量 1130
try 块中的 return 语句执行成功后,并不马上返回,而是继续执行 finally 块中的语句,
如果此处存 在 return 语句,则在此直接返回,丢弃 try 块中的返回值。

finally 中写return , eclipse 会提示 
finally block does not complete  normally
 
public abstract class NoReturnInFinally {
	
	private static final Random rand = new Random();
	
	public static void main(String[] args) throws Exception {		
		for(int i=0;i<20;i++){
			System.out.println(run());
		}
	}
	
	private static String run(){
		try{		
			int tmp = rand.nextInt(10);
			if((tmp%2) == 0){
				throw new Exception("error");
			}	
			return "ok";		
		}catch(Throwable e){	
			return "error";
		}finally{
			return "xxx";
		}	
	}
}
 
 
run返回结果 都是  xxx

上一篇     下一篇
手机4G信号突然变成2G信号

JVM性能分析利器 JMC 和 JFR

Timer和ScheduledExecutorService的区别

jcmd PerfCounter 说明

集合遍历删除注意点

java编码规范