什么是Java中的异常?

q1871901600 发布于 2024-11-19 31 次阅读


异常是在程序执行过程中发生的不正常事件,它会中断程序的正常流程。如果没有处理,程序可能会突然终止。异常可以是检查型(checked)异常,也可以是非检查型(unchecked)异常。检查型异常是编译时检查的异常,必须显式捕获或抛出;非检查型异常包括运行时异常(RuntimeException)和错误(Error),它们不需要显式捕获,通常是程序逻辑错误或系统问题。

检查型异常(Checked Exception)

import java.io.FileReader;
import java.io.IOException;

public class CheckedExceptionExample {
    public static void main(String[] args) {
        try {
            FileReader fileReader = new FileReader("example.txt");
            int i;
            while ((i = fileReader.read()) != -1) {
                System.out.print((char) i);
            }
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

在这个例子中,FileReader构造函数可能会抛出IOException,这是一个检查型异常。我们必须在try-catch块中处理它。

非检查型异常(Unchecked Exception)

public class UncheckedExceptionExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        try {
            System.out.println(numbers[10]); // 这将抛出 ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Index out of bounds.");
            e.printStackTrace();
        }
    }
}

在这个例子中,尝试访问数组的非法索引将抛出ArrayIndexOutOfBoundsException,这是一个非检查型异常。

自定义异常

// 自定义异常类
class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

public class CustomExceptionExample {
    public static void validateAge(int age) throws InvalidAgeException {
        if (age < 0 || age > 150) {
            throw new InvalidAgeException("Age must be between 0 and 150.");
        }
    }

    public static void main(String[] args) {
        try {
            validateAge(-5);
        } catch (InvalidAgeException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}
一个会写python的Java工程师
最后更新于 2024-11-19