Java的try-catch-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;
	}
}

都会报错,如下则不会:  

try {} 
catch (Exception e) {} 
finally {
	try {
		throw new Exception();
	} catch (Exception e) {

	}
}

try {} 
catch (Exception e) {} 
finally {
	L: {
		break L;
	}
}

 

猜你喜欢

转载自www.cnblogs.com/extjs4/p/9375400.html