- 自定义异常类:
- 在Java中自定义异常类,需要继承
Exception
类(如果是受检异常)或RuntimeException
类(如果是非受检异常)。
- 示例代码如下:
public class MyBusinessException extends Exception {
public MyBusinessException(String message) {
super(message);
}
}
- 使用异常链实现包含系统异常信息:
- 当在数据处理过程中发生错误并需要抛出自定义异常,同时包含之前发生的系统异常信息时,可以利用异常链。在自定义异常类的构造函数中,使用
super(String message, Throwable cause)
构造函数,其中cause
就是之前发生的系统异常。
- 示例代码如下:
public class DataProcessor {
public static void processData() throws MyBusinessException {
try {
// 模拟可能抛出系统异常的代码
int result = 10 / 0;
} catch (ArithmeticException e) {
// 抛出自定义异常,并将系统异常作为异常链的原因
throw new MyBusinessException("数据处理过程中发生错误", e);
}
}
}
public class Main {
public static void main(String[] args) {
try {
DataProcessor.processData();
} catch (MyBusinessException e) {
System.out.println("捕获到自定义异常: " + e.getMessage());
e.getCause().printStackTrace();// 打印系统异常信息
}
}
}