java里面不是可以保證finally一定會執行的么,為什么不可以在finally塊做return?
細細看道來:debug一下這個函數,就會驚訝的發現, 里面拋出的異常會被finally吃掉。 這也就是為什么會被警告的原因。
@SupPRessWarnings( "finally" )private boolean isReturnWithinFinally(){ try { if ( true ) throw new RuntimeException(); } finally { return(true); /* This hides the exception */ }}那么,下面這樣會不會ok呢?先把異常處理public static void main( String[] args ){ try{ throw new RuntimeException(); }catch ( Exception e ) { /* */ } finally { return; }}結論是:依舊不行。java里面的異常分為可不獲和不可捕獲兩類,即便使用到catch塊,也會導致非捕獲的錯誤被finally吃掉。因此,return一定要放到finally外面。
新聞熱點
疑難解答