Java异常处理

Java 异常处理是编程中的重要一环,它能让程序在遇到错误时不中断,而是优雅地处理异常,继续执行或给出合理的反馈。掌握异常处理是编写健壮程序的基础。

异常是指程序运行过程中发生的错误情况,通常会导致程序的中断。Java 中的异常分为两类:

1.编译时异常(Checked Exception):必须显式处理(如 IOExceptionSQLException 等)。

2.运行时异常(Unchecked Exception):可选处理,通常由代码逻辑错误引发(如 NullPointerExceptionArrayIndexOutOfBoundsException 等)

在 Java 中,所有异常都继承自 Throwable 类。Throwable 有两个主要的子类:

1.Error:表示 JVM 的错误(如内存溢出 OutOfMemoryError),一般不需要处理。

2.Exception:表示程序的异常。它可以进一步分为 检查异常CheckedException)和 未检查异常UncheckedException)。

常见异常类型

异常类型 说明 示例
NullPointerException 访问或操作空对象 String str = null; str.length();
ArithmeticException 算术计算错误(如除以零) int result = 10 / 0;
ArrayIndexOutOfBoundsException 数组越界访问 int[] arr = new int[5]; arr[10] = 100;
FileNotFoundException 文件未找到 FileReader file = new FileReader("nonexistent.txt");
IOException 输入输出异常 FileInputStream in = new FileInputStream("file.txt");

 捕获和处理异常

1.try-catch语句

try {
    // 可能抛出异常的代码
    int result = 10 / 0; // 除零异常
} catch (ArithmeticException e) {
    // 异常处理代码
    System.out.println("捕获到异常: " + e.getMessage());
} finally {
    // 无论是否发生异常,都会执行的代码
    System.out.println("最终代码块,无论是否发生异常都会执行");
}

 try:放置可能抛出异常的代码。

catch:捕获并处理异常,通常是具体的异常类型。

finally:最终执行的代码块(如资源释放、清理工作等)。

2.多catch语句

try {
    int[] arr = new int[5];
    System.out.println(arr[10]);  // 数组下标越界
} catch (ArithmeticException e) {
    System.out.println("算术错误");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("数组下标越界");
} catch (Exception e) {
    System.out.println("其他异常");
}

当遇到异常时,异常会被丢给第一个catch,如果与第一个catch语句参数列表里的类型相同,则在此被捕获,否则依次向下传递。

3.捕获多个异常

try {
    int[] arr = new int[5];
    System.out.println(arr[10]);  // 数组下标越界
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
    System.out.println("捕获异常: " + e.getClass().getName());
}

比如

public void doSomething() {
    int[] arr = new int[3];
    int x = 10 / 0; // 可能出现 ArithmeticException
    System.out.println(arr[5]); // 可能出现 ArrayIndexOutOfBoundsException
}

 捕获代码可写成
 

try {
    int[] arr = new int[3];
    int x = 10 / 0;
    System.out.println(arr[5]);
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
    System.out.println("发生了算术异常或数组越界:" + e.getClass().getSimpleName());
}

 声明异常

 有些异常无法在方法内处理,而是需要由调用者来处理(例如 IOException )。这时,我们使用关键字 throws 声明异常。

public void readFile(String filePath) throws IOException {
    FileReader file = new FileReader(filePath);
    BufferedReader reader = new BufferedReader(file);
    reader.readLine();
    reader.close();
}

自定义异常 

当标准 Java 异常不足以表达业务逻辑时,可以定义自己的异常类。

// 继承 Exception 或 RuntimeException(Unchecked)
public class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);  // 调用父类构造方法
    }
}

示例:
 

public void checkAge(int age) throws InvalidAgeException {
    if (age < 0) {
        throw new InvalidAgeException("年龄不能为负数");
    }
    System.out.println("合法年龄");
}

以上就是对Java异常处理的学习,如有错误,欢迎指正!

你可能感兴趣的:(java,开发语言)