Java异常02:捕获和抛出异常
异常必须捕获处理或者抛出让调用者处理,二选一
捕获异常(try...catch...finally)
public class Hello {
public static void main(String[] args) {
int a = 1;
int b = 0;
//try...catch...finally关键字捕获异常处理,快捷键ctrl + alt + T
try {
System.out.println(a / b);
} catch (Exception e) { //指定要捕获的异常类型,默认是Exception
System.out.println("这是Exception");
} catch (Error e){
System.out.println("这是Error");
} catch (Throwable e) { //catch代码块可以嵌套,最多只会执行一个。异常的范围顺序应由小到大
System.out.println("这是Throwable");
}
finally {
//finally代码块如果写了一定会执行,处理IO、资源等善后工作,如执行scanner.close(),可选
System.out.println("finally代码块一定会执行");
}
}
}
- 在多重catch块后面,可以加一个catch (Exception e)来处理可能会遗漏的异常
- 尽量使用finally语句块释放占用的资源
抛出异常(throw,throws)
public class Hello {
public static void main(String[] args) {
//创建一次性匿名对象
new Hello().test(1, 0);
}
//抛出异常让调用者处理
public void test(int a, int b) throws ArithmeticException { //throws关键字,方法外抛出异常类
if (b == 0){
throw new ArithmeticException(); //throw关键字,方法内抛出异常类的对象或引用
}
System.out.println(a / b); //正常结束
}
}
自定义异常
步骤
- 定义异常子类,重写toString()方法,用来打印异常信息
- 在可能发生异常的方法中主动抛出异常或者捕获,二选一
- 如果没有捕获,那么调用该方法时再二选一
public class Hello {
public static void main(String[] args) {
//3.调用抛出了异常的方法,一定要捕获或者再次抛出
try {
test(11);
} catch (MyException e) {
System.out.println(e); //e是异常类对象,直接打印e等同于e.toString()
}
// //3.异常已被捕获,无需再处理
// test(11);
}
//2.主动抛出(throw和throws配合)
static void test(int a) throws MyException {
System.out.println("传递的参数为:" + a);
//定义异常的规则
if (a > 10){
throw new MyException(a);
}
System.out.println("OK");
}
// //2.自己捕获处理(try...catch和throw配合)
// static void test(int a) {
// System.out.println("传递的参数为:" + a);
// if (a > 10) {
// try {
// throw new MyException(a);
// } catch (MyException e) {
// System.out.println(e);
// }
// }
// //catch后的语句会继续执行,因此无异常才执行的语句要放进else语句
// else {
// System.out.println("OK");
// }
// }
}
//1.定义异常子类,必须继承其他异常类
class MyException extends Exception{
int a;
public MyException(int a){
this.a = a;
}
//重写toString()方法,可以自定义打印的异常信息
@Override
public String toString() {
return "MyException{" + a + '}';
}
}