以下是一个示例代码,演示了如何捕获并重新抛出相同的自定义异常:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class Example {
public static void main(String[] args) {
try {
doSomething();
} catch (CustomException e) {
System.out.println("Caught custom exception: " + e.getMessage());
}
}
public static void doSomething() throws CustomException {
try {
// 可能会抛出自定义异常的代码
throw new CustomException("Something went wrong");
} catch (CustomException e) {
// 捕获并重新抛出相同的自定义异常
throw e;
}
}
}
在上面的示例中,doSomething()
方法可能会抛出CustomException
自定义异常。在该方法内部,我们使用try-catch
块来捕获该异常,并通过throw
语句重新抛出相同的异常。这样做的好处是,在main()
方法中的try-catch
块中,我们可以捕获并处理doSomething()
方法抛出的自定义异常。
请注意,在捕获并重新抛出异常时,我们使用了throw e;
语句,而不是throw new CustomException(e.getMessage());
语句。这是因为我们希望保留原始异常的信息和堆栈跟踪,而不是创建一个新的异常对象。