189. Java 异常 - Java 异常类型详解:三种异常类型

59 阅读2分钟

189. Java 异常 - Java 异常类型详解:三种异常类型

在 Java 中,**异常(Exception)**可以分为三大类:

  1. Checked Exception(受检异常)
  2. Error(错误)
  3. ⚠️ Runtime Exception(运行时异常)

1️⃣ Checked Exception(受检异常)

✅ 概念:

受检异常代表程序外部因素导致的异常情况,程序应当预料并进行处理,比如文件不存在、网络连接失败等。

🧠 特点:

  • 必须使用 try-catch 或 throws 来处理,否则编译报错(⚠️ Catch or Specify Requirement
  • 这些异常是可以被程序预测并恢复

📌 常见示例:

import java.io.*;

public class FileDemo {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("notfound.txt"); // 文件不存在
        } catch (FileNotFoundException e) {
            System.out.println("⚠️ 文件未找到,请检查路径!");
        }
    }
}

📚 典型类:

  • IOException
  • SQLException
  • FileNotFoundException
  • ClassNotFoundException

2️⃣ Error(错误)

❗ 概念:

Error 表示 JVM 或系统层级的严重问题,通常程序无法预料、无法恢复

比如内存溢出、虚拟机崩溃等。我们通常不建议程序去捕获或处理它们。

📌 示例:

public class OutOfMemoryDemo {
    public static void main(String[] args) {
        int[] bigArray = new int[Integer.MAX_VALUE]; // 可能导致 OutOfMemoryError
    }
}

虽然你可以用 try-catch 包起来,但程序恢复也基本无望:

try {
    int[] bigArray = new int[Integer.MAX_VALUE];
} catch (OutOfMemoryError e) {
    System.err.println("系统资源不足,程序无法继续!");
}

📚 典型类:

  • OutOfMemoryError
  • StackOverflowError
  • InternalError
  • IOError

🚫 特点:

  • 不属于 Checked Exception(无需 try-catch
  • 不受 Catch or Specify Requirement 约束

3️⃣ Runtime Exception(运行时异常)

⚠️ 概念:

运行时异常通常是由程序逻辑错误引起的,比如空指针、除以 0、数组越界等。

这类异常不是程序运行环境的问题,而是开发者自己代码的问题。

📌 示例:

public class RuntimeDemo {
    public static void main(String[] args) {
        String name = null;
        System.out.println(name.length()); // NullPointerException
    }
}

虽然你可以捕获:

try {
    String name = null;
    System.out.println(name.length());
} catch (NullPointerException e) {
    System.out.println("变量未初始化!");
}

⚠️ 但更推荐的是:修复代码逻辑问题,而不是捕获异常


📚 典型类:

  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • IllegalArgumentException
  • ArithmeticException

🧠 特点:

  • 不属于 Checked Exception
  • 可以被 try-catch 捕获
  • 不强制捕获或声明(不受 Catch or Specify Requirement 约束)

🧾 总结对比表

异常类型是否必须 try-catch 或 throws可恢复性原因来源常见类
✅ Checked Exception✅ 是✅ 通常可恢复外部环境错误IOException, SQLException
⚠️ Runtime Exception❌ 否❌ 程序 bug编码逻辑错误NullPointerException, ArithmeticException
❗ Error❌ 否❌ 基本不可恢复系统/JVM 错误OutOfMemoryError, StackOverflowError