java:异常处理
finally
?? finally的作用是為了保證無(wú)論出現(xiàn)什么情況,finally塊里的代碼一定會(huì)被執(zhí)行。
? ①finally塊中的語(yǔ)句什么時(shí)候被執(zhí)行?
? ? ?任何語(yǔ)句執(zhí)行都只能在return前執(zhí)行,因此finally塊里的代碼也是在return前執(zhí)行的。
? ? ?并且 try-finally或者catch-finally中都有return, 那么finally塊中的return語(yǔ)句將會(huì)覆蓋別出的return語(yǔ)句,最終返回調(diào)用者那里的是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,并且不是運(yùn)行時(shí)異常的異常都是檢查異常。最常見的檢查異常是IO異常和SQL異常。java編譯器強(qiáng)制程序去捕獲檢查異常。
? 運(yùn)行時(shí)異常: ? 編譯器沒有強(qiáng)制程序?qū)\(yùn)行時(shí)異常進(jìn)行捕獲并處理。
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();}}?
總結(jié)
- 上一篇: java:数组
- 下一篇: JAVA中return与finally的