2012-05-20 19:22:38Morris
[JAVA] Exception 例外處理實驗
public class A {
public static void main(String[] args) {
try {
method(50);
} catch(Exception e) {
System.out.println("main catch block");
}
System.out.println("main block");
}
public static void method(int num) throws Exception {
try {
if(num > 0)
throw new Exception();
if(num < 0)
throw new NumberFormatException();
} catch (NumberFormatException exp) {
System.out.println("NumberFormat");
} finally {
System.out.println("In finally block");
}
System.out.println("Method block");
}
}
範例輸出:
In finally block
main catch block
main block
在 method 可能丟出抓不到 catch exception,
因此會在 main 裡面被抓住, 因此清楚了解的以為跟 return 一樣 finally block 會被處理到,
但是我錯了, 它還是會先處理完。
結論 : finally 一定會被處理到
public static void main(String[] args) {
try {
method(50);
} catch(Exception e) {
System.out.println("main catch block");
}
System.out.println("main block");
}
public static void method(int num) throws Exception {
try {
if(num > 0)
throw new Exception();
if(num < 0)
throw new NumberFormatException();
} catch (NumberFormatException exp) {
System.out.println("NumberFormat");
} finally {
System.out.println("In finally block");
}
System.out.println("Method block");
}
}
範例輸出:
In finally block
main catch block
main block
在 method 可能丟出抓不到 catch exception,
因此會在 main 裡面被抓住, 因此清楚了解的以為跟 return 一樣 finally block 會被處理到,
但是我錯了, 它還是會先處理完。
結論 : finally 一定會被處理到