java:异常处理
finally
?? finally的作用是為了保證無論出現(xiàn)什么情況,finally塊里的代碼一定會被執(zhí)行。
? ①finally塊中的語句什么時候被執(zhí)行?
? ? ?任何語句執(zhí)行都只能在return前執(zhí)行,因此finally塊里的代碼也是在return前執(zhí)行的。
? ? ?并且 try-finally或者catch-finally中都有return, 那么finally塊中的return語句將會覆蓋別出的return語句,最終返回調用者那里的是finally中return的值。
public static int testFinally(){try{//int a = 5/0;return 1;}catch(Exception e){System.out.println("Exception");return 2;}finally{System.out.println("finally");return 3;}}public static void main(String[] args) {int r = testFinally();System.out.println(r);}??
Exception:
? 檢查異常 : ? ? 所有繼承自Exception,并且不是運行時異常的異常都是檢查異常。最常見的檢查異常是IO異常和SQL異常。java編譯器強制程序去捕獲檢查異常。
? 運行時異常: ? 編譯器沒有強制程序對運行時異常進行捕獲并處理。
public void doSomething() throws ArithmeticException{System.out.println();}public void doSomething2() throws IOException{System.out.println();}@Testpublic void testException(){doSomething();try {doSomething2();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}?
總結
- 上一篇: java:数组
- 下一篇: JAVA中return与finally的