【狂神说Java】异常处理机制及自定义异常
捕获异常
自动生成try...catch快捷键:ctrl+alt+t
public class TryCatch {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { // 程序运行监控
System.out.println(a / b);
} catch (ArithmeticException e) { // 捕获异常
System.out.println("错误1");
e.printStackTrace();// 打印错误信息
} catch (Exception t) { // 异常捕获可以多个catch,从小到大
System.out.println("错误2");
t.printStackTrace();// 打印错误栈信息
} finally {
System.out.println("不管怎么样最后都会执行到"); // 可以不要finally
}
}
}
抛出异常
throw new 异常(),主动抛出异常一般在方法中使用
假如在方法中没法处理异常则需要在方法上抛出异常throws 异常
public class TryCatch {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { // 程序运行监控
if (0 == b){
throw new ArithmeticException(); //主动抛出异常
}
System.out.println(a / b);
} catch (ArithmeticException e) { // 捕获异常
System.out.println("错误1");
e.printStackTrace();// 打印错误信息
} catch (Exception t) { // 异常捕获可以多个catch,从小到大
System.out.println("错误2");
t.printStackTrace();// 打印错误信息
} finally {
System.out.println("不管怎么样最后都会执行到"); // 可以不要finally
}
}
}
自定义异常
- 创建自定义异常类继承Exception类。
- 在方法中通过throw关键字抛出异常对象。
- 如果在当前抛出异常的方法中处理异常,可以使用try-catch语句捕获并处理;否则在方法的声明处需要用throws关键字指明要抛出给方法调用者的异常,继续进行下一步操作。
- 在出现异常方法的调用者中捕获并处理异常。
// 自己写的异常
public class MyException extends Exception{
// 传递数字> 10 抛出异常
private int detail;
public MyException(int a) {
// 构造方法,在throw new MyException时调用
this.detail = a;
}
@Override
public String toString() {
// 抛出异常时打印到控制台的数据
return "MyException{" +
"detail=" + detail +
'}';
}
}
class TestMyexception{ // 测试用
static void test(int a) throws MyException {
// 方法中没处理异常需要throws
if(a>10){
throw new MyException(a);
}
System.out.println("OK");
}
public static void main(String[] args) {
// 用try catch处理异常
try {
test(11);
} catch (MyException e) {
e.printStackTrace();
}
}
}

浙公网安备 33010602011771号