java异常机制 _2 _异常处理
异常梳处理机制
- 抛出异常
- 捕获异常
- 异常处理五个关键字:
try 、 catch 、 finally、 throw、 throws
代码1:
package com.wlw.exception;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {//try监控区域
System.out.println(a/b);
}catch (Exception e){ //catch(想要捕获的异常类型!)捕获异常
System.out.println("程序出现异常");
}finally { //一定会执行,处理善后工作(可以不要)
System.out.println("finally1");
}
System.out.println("========================");
/*
假设要捕获多个异常,要从小到大
*/
try {
//new Test().a(); // 执行结果:程序出现异常 Error e
if(b == 0){
throw new ArithmeticException();//主动抛出异常
}
System.out.println(a/b); // 执行结果:程序出现异常 Exception e
}catch (Error e){
System.out.println("程序出现异常 Error e");
}catch (Exception e){
System.out.println("程序出现异常 Exception e");
}catch (Throwable t){
System.out.println("程序出现异常 Throwable t");
} finally {
System.out.println("finally2");
}
}
public void a(){
b();
}
public void b(){
a();
}
}
代码2:
package com.wlw.exception;
public class Test2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
// 快捷键 Ctrl + Alt + T ,自动帮我们补全一些结构
try {
System.out.println(a/b);
} catch (Exception e) {
e.printStackTrace(); //打印错误信息
} finally {
}
}
}
代码3:
package com.wlw.exception;
public class Test3 {
public static void main(String[] args) {
try {
new Test3().test(1,0);
} catch (ArithmeticException e) {
System.out.println("出现异常");
e.printStackTrace();
}
}
//假设这个方法处理不了这个异常,就抛出,throws
public void test(int a,int b) throws ArithmeticException{
/*if (b == 0) { //throw throws
throw new ArithmeticException();//主动抛出异常,一般在方法中使用
}*/
System.out.println(a / b);
}
}
/*
执行结果:
出现异常
java.lang.ArithmeticException: / by zero
at com.wlw.exception.Test3.test(Test3.java:20)
at com.wlw.exception.Test3.main(Test3.java:7)
*/
快捷键小结
Alt + Insert:生成构造方法、get/set、重写方法、
Ctrl + Alt + T :try {}catch(){},循环、判断等一些结构自动补全