在Java中,可以通过throw
关键字捕获异常并重新抛出它,但可以重新抛出非异常类型的异常。以下是一个示例代码:
public class Main {
public static void main(String[] args) {
try {
method1();
} catch (CustomException e) {
System.out.println("Caught CustomException: " + e.getMessage());
}
}
public static void method1() throws CustomException {
try {
method2();
} catch (Exception e) {
throw new CustomException("An error occurred", e);
}
}
public static void method2() {
throw new RuntimeException("This is not an exception");
}
}
class CustomException extends Exception {
public CustomException(String message, Throwable cause) {
super(message, cause);
}
}
在上述示例中,method2()
方法抛出了一个RuntimeException
,该异常被method1()
方法捕获并重新抛出为一个自定义异常CustomException
。main()
方法捕获并处理了CustomException
。
输出结果为:
Caught CustomException: An error occurred