Aar*_*ath 40 java finally try-catch
当try-catch结束时,总是执行"finally"块,无论是否异常.但是,try-catch之外和之后的每一行代码总是被执行.那么,我为什么要使用finally语句呢?
例:
try {
//code...
} catch (Exception e) {
//code...
} finally {
System.out.println("This line is always printed");
}
System.out.println("Also this line is always printed !! So why to use 'finally'?? ");
Run Code Online (Sandbox Code Playgroud)
Den*_*ret 22
最有用的情况是需要释放一些资源时:
InputStream is = ...
try {
//code...
} catch (Exception e) {
//code...
} finally {
is.close();
}
Run Code Online (Sandbox Code Playgroud)
更一般地说,即使在执行期间发生异常,您也希望确保代码在最后执行时使用它:
long startTime = System.currentTimeMillis();
try {
//code...
} catch (Exception e) {
//code...
} finally {
long endTime = System.currentTimeMillis();
System.out.println("Operation took " + (endTime-startTime) + " ms");
}
Run Code Online (Sandbox Code Playgroud)
始终执行此finally
块的想法是,整个块之后的第一行不是这种情况
catch
块让一些可抛出的传球System.out.println
如果try块中抛出的异常被catch块实际捕获并且执行没有被例如return语句中断,则仅运行last (在finally块之后).
在你的榜样,finally块将始终运行,但运行将继续以往的finally块,如果没有Error
在try块抛出(它不会被抓到),如果没有Throwable
在catch块抛出并没有其他语句,将中断执行.
但也总是执行 try-catch 之外和之后的每一行代码。
嗯,并非总是如此。例如,我们可以 throwError
不是 Exceptionuon 的子类型,而是 Throwable,因此它不会被catch(Exception e) {..}
. 在这种情况下,try
块将控制流移出方法的相应finally
部分将被调用,但之后的代码不会。
看看这个代码
public static void main(String[] args) {
try{
//...
throw new Error("something went terribly wrong");
} catch (Exception e) {//will NOT catch Error
e.printStackTrace();
} finally{//this will be invoked regardless of what happens in try,
System.out.println("finally block");
}
//if Error will be thrown in above `try` it will move flow of control
//from this method, which will prevent it from reaching
//this place and executing code after this comment
System.out.println("after finally... may not be executed");
}
Run Code Online (Sandbox Code Playgroud)