2.编写一个自定义异常类,在另一个类中抛出至少三种异常并捕捉,要求其中一种异常是前面的自定义异常Java
时间: 2023-07-15 14:13:31 浏览: 100
自定义异常类 MyException:
```
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
```
另一个类中抛出三种异常并捕捉:
```
public class TestException {
public static void main(String[] args) {
try {
// 抛出自定义异常
throw new MyException("This is a custom exception.");
// 抛出数组越界异常
int[] arr = {1, 2, 3};
System.out.println(arr[3]);
// 抛出空指针异常
String str = null;
System.out.println(str.length());
} catch (MyException e) {
System.out.println("Caught MyException: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
}
}
}
```
阅读全文