java编写两个自己定义的异常类,然后在编写一个类,在其中编写两个方法f1()和f2()。在f2() 中抛出自己定义的第一个常类对象,在f1() 中调用f2(),并捕捉其中的异常,然后在catch字句中抛出第二个异常。
时间: 2023-06-14 13:07:48 浏览: 40
Java异常的捕获及处理
好的,下面是示例代码:
自定义异常类1:
```java
public class CustomException1 extends Exception {
public CustomException1(String message) {
super(message);
}
}
```
自定义异常类2:
```java
public class CustomException2 extends Exception {
public CustomException2(String message) {
super(message);
}
}
```
编写的类:
```java
public class ExceptionDemo {
public void f1() throws CustomException2 {
try {
f2();
} catch (CustomException1 e) {
throw new CustomException2("Caught CustomException1 in f1() method");
}
}
public void f2() throws CustomException1 {
throw new CustomException1("CustomException1 thrown from f2() method");
}
}
```
在主函数中进行调用:
```java
public static void main(String[] args) {
ExceptionDemo demo = new ExceptionDemo();
try {
demo.f1();
} catch (CustomException2 e) {
System.out.println(e.getMessage());
}
}
```
输出:
```
Caught CustomException1 in f1() method
```
阅读全文