Java——异常处理
Java中的异常处理是一种机制,用于处理程序运行过程中可能发生的异常情况,以确保程序能够正常运行或进行适当的处理。异常处理主要通过 try-catch-finally 块来实现。
1. try-catch
try 块用于包裹可能会抛出异常的代码块, catch 块用于捕获并处理异常,可以使用多个 catch 块来处理不同类型的异常。
代码如下:
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]); // 引发数组越界异常
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界异常:" + e.getMessage());
} catch (Exception e) {
System.out.println("其他异常:" + e.getMessage());
}
}
}
2. finally
finally 块用于在 try-catch 块执行完毕后无论是否发生异常都会执行的代码块,通常用于释放资源或清理操作。
代码如下:
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
int result = 10 / 0; // 引发算术异常
System.out.println("结果:" + result);
} catch (ArithmeticException e) {
System.out.println("算术异常:" + e.getMessage());
} finally {
System.out.println("执行finally块");
}
}
}
3. 抛出异常
可以使用 throw
关键字手动抛出异常,通常用于在代码中检测到错误并主动抛出异常。
代码如下:
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
int age = -1;
if (age < 0) {
throw new IllegalArgumentException("年龄不能为负数");
}
} catch (IllegalArgumentException e) {
System.out.println("参数异常:" + e.getMessage());
}
}
}
常见运行时异常
- ArrayIndexOutOfBoundsException: 数组索引越界异常
- NoSuchElementException: 迭代器遍历没有此元素异常
- ArithmeticException: 算术异常
- NullPointerException: 空指针异常
- ClassCastException: 类型转换异常
上一篇 Java常见的判空方式汇总。 |
欢迎点赞、收藏、评论!!!
| 下一篇 面试官:说一说Map不同实现类的对比以及使用场景 |