自定义异常的抛出和捕获;Java内置异常的捕获与处理
时间: 2024-03-05 13:50:11 浏览: 15
好的,我来简单回答你的问题。
自定义异常的抛出和捕获:
在Java中,我们可以通过自定义异常来处理一些特定的业务逻辑异常。我们可以通过定义一个继承自Exception或RuntimeException的类来实现自定义异常。在代码中,当我们需要抛出这个自定义异常时,可以使用throw关键字将其抛出。而当我们需要捕获这个异常时,可以使用try-catch语句来实现。比如:
```
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public class Test {
public static void main(String[] args) {
try {
throw new MyException("这是我自定义的异常");
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}
```
Java内置异常的捕获与处理:
在Java中,除了我们自定义的异常之外,还有很多内置的异常类,例如NullPointerException、ArrayIndexOutOfBoundsException等等。当程序运行过程中出现这些异常时,会抛出对应的异常类。我们可以通过try-catch语句来捕获这些异常,然后进行处理。比如:
```
public class Test {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
System.out.println(arr[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组下标越界了");
}
}
}
```
当我们运行这段代码时,由于数组下标越界了,程序会抛出ArrayIndexOutOfBoundsException异常,然后被catch块捕获并处理。