二、Java异常处理机制
异常处理的五个关键字:try、catch、finally、throw、throws
1.捕获异常
Ctrl+Alt+T 快捷键,选中语句后,自动生成if\else\try\catch等代码块包裹
package com.exception;
public class Demo01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {//try监控局域
System.out.println(a / b);
} catch (ArithmeticException e) {//捕获异常
System.out.println("程序出现异常,变量b不能为0");
} finally {//处理善后工作,可选不要
System.out.println("finally");
}
//可以不要,但是IO资源时,需要用来关闭
}
}
package com.exception;
public class Demo01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
//假设要捕获多个异常,要从小到大
try {//try监控局域
System.out.println(a / b);
} catch (ArithmeticException e) {//捕获异常
System.out.println("程序出现ArithmeticException异常");
} catch (Error e) {//
System.out.println("程序出现Error异常");
} catch (Exception e) {//
System.out.println("程序出现Exception异常");
} catch (Throwable e) {//等级最高的就是Throwable,最大的要写在最后面
System.out.println("程序出现Throwable异常");
} finally {//处理善后工作,可选不要
System.out.println("finally");
}
//可以不要,但是IO资源时,需要用来关闭
}
public void a() {
b();
}
public void b() {
a();
}
}
2.抛出异常
package com.exception;
public class Demo01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
new Demo01().test(a, b);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
//假设方法中
public void test(int a, int b) {
if (b == 0) {//主动的抛出一个异常 throw!!(不是throws)
throw new ArithmeticException();//主动抛出异常,一般在方法中使用
}
System.out.println(a / b);
}
}
throw 和 throws 的区别
1)throw:
- 表示方法内抛出某种异常对象。
- 如果异常对象是非 RuntimeException 则需要在方法申明时加上该异常的抛出 即需要加上 throws 语句 或者 在方法体内 try catch 处理该异常,否则编译报错执行到 throw 语句则后面的语句块不再执行
2)throws:
- 方法的定义上使用 throws 表示这个方法可能抛出某种异常,
- 需要由方法的调用者进行异常处理