转载地址:http://www.cnblogs.com/interdrp/p/4095846.html
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外面。