day29 捕获和抛出异常
异常处理机制
- 抛出异常
- 捕获异常
- 异常处理五个关键字
try,catch,finally,throw,throws
package com.exception;
public class Test {
public static void main(String[] args) {
//假设要捕获多个异常:从小到大!
try {
new Test().test(1, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
public void test(int a,int b)throws ArithmeticException{//假设方法中,处理不了这个异常。就在方法上抛出这个异常
if (b == 0) {//throw throws
throw new ArithmeticException();//主动地抛出异常,一般在方法中使用
}
}
/*//假设要捕获多个异常:从小到大!
int a =0;
int b =1;
} //catch必须要,finally可以不要,假设有IO,资源,关闭,都放在finally里
try {//try监控区域
if (b == 0) {//throw throws
throw new ArithmeticException();//主动地抛出异常
}
System.out.println(a / b);
} catch (Error e) {//catch 捕获异常
System.out.println("Error");
} catch (Exception e) {//catch 捕获异常
System.out.println("Exception");
} catch (Throwable t) {//catch 捕获异常
System.out.println("Throwable");
} finally {//处理善后工作
System.out.println("finally");
}
* */
}
package com.exception;
public class Test2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
System.out.println(a/b);//ctrl+alt+t
} catch (Exception e) {
System.exit(1);
e.printStackTrace();//打印错误的栈信息
}
}
}