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;
	}
}

都会出现警告信息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_第1张图片

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(Java的try-catch-finally)