异常处理机制
- 抛出异常
- 捕获异常
- 异常处理五个关键字:
try,catch,finally,throw,throws
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { //try:监控区域
System.out.println(a/b);
}catch (ArithmeticException a1){ //catch:捕获异常
System.out.println("程序出现异常,变量b不能为0");
}finally{ //finally:处理善后工作,无论出不出异常,都会被执行
System.out.println("finally");
}
//finally区域可以不要,假设IO,资源,关闭!
}
输出:没有红色报错了!
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { //try:监控区域
new Test().a();
//System.out.println(a/b);
}catch (Throwable t){ //catch(想要捕获的异常类型!)捕获异常
System.out.println("程序出现异常");
}finally{ //finally:处理善后工作,无论出不出异常,都会被执行
System.out.println("finally");
}
//finally区域可以不要,假设IO,资源,关闭!
}
public void a(){
b();
}
public void b(){
a();
}
}
输出:
catch(后面这个括号里面是想要捕获的异常类型!)
如果有多个catch,用a/b做例子,他会捕获哪个异常?
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
//假设要捕获多个异常:从小到大的捕获!
try { //try:监控区域
//new Test().a();
System.out.println(a/b);
}catch (Error e1){ //catch(想要捕获的异常类型!) 捕获异常
System.out.println("Error!");
} catch (Exception e){
System.out.println("Exception!");
}catch (Throwable t){ //最大的异常要写在最后面,不然如果在前面,后面的异常就不会执行了
System.out.println("Throwable!");
}finally{ //finally:处理善后工作,无论出不出异常,都会被执行
System.out.println("finally");
}
//finally区域可以不要,假设IO,资源,关闭!
}
public void a(){
b();
}
public void b(){
a();
}
}
可以看出捕获了Exception:
如果最大的异常Throwable和Exception换个位置,就会立马报错
意思是异常的. lang.Exception’已经被捕获,所以Throwable异常类型要放在最后面。参考下图:
假设要捕获多个异常:要从小到大的捕获!不然就会出现上述报错!
捕获异常try/catch/finally可以快捷生成:
Ctrl+Alt+T,选择8.try/catch/finally
public class Test2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
//生成try/catch/finally快捷键:Ctrl+Alt+T,选择8.try/catch/finally
try {
System.out.println(a/b);
} catch (Exception e) {
System.exit(886);//程序结束,输出Process finished with exit code 886(进程已完成,退出代码为886)
e.printStackTrace();//打印错误的栈信息,打印的还是红色的报错信息。一般还是写自己的判断,比如输出一段话或者让程序停止等
} finally {
}
}
}
throw和throws用法
public class Test03 {
public static void main(String[] args) {
try { //如果没有try/catch捕获异常,程序就停止了,好处就是try/catch捕获异常程序可以继续执行
new Test03().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
} finally {
}
}
//假设这个方法中,处理不了这个异常。方法上抛出异常
public void test(int a,int b) throws ArithmeticException{
if (b==0){ //主动的抛出异常 throw throws
throw new ArithmeticException();//主动抛出一个异常,一般在方法中使用
}
//System.out.println(a/b);/没有这一句a/b,它也会抛出异常
}
}