public class Main {
static void process(String string , String string2) throws Exception {
try {
int a = Integer.valueOf(string);
int b = Integer.valueOf(string2);
a = a/b;
} catch (NumberFormatException e) {
System.out.println("process()捕獲了NumberFormatException");
}catch (ArithmeticException e) {
System.out.println("process()捕獲了ArithmeticException");
throw new Exception("除法異常被拋出3搿!!");
}finally{
System.out.println("finally()");
}
}
public static void main(String[] args) throws Exception{
process("3232" , "0");
}
}
運行情況:
process()捕獲了ArithmeticException
finally()
Exception in thread "main" java.lang.Exception: 除法異常被拋出Q丬健=溆啤熬荆!
at Main.process(Main.java:12)
at Main.main(Main.java:19)
- 我們可以看到是先執(zhí)行了finally中的方法,然后Exception異常才被拋到main方法中绸狐,最終在main方法中被捕獲卤恳。是符合我們的期望的。
異常的三大原則
- 明確異常信息
- 盡快拋出(快速失敽蟆)
- 延遲捕獲