受检异常(Checked Exception)


2. 受检异常(Checked Exception)(续)

(1)IOException

描述:
IOException 是 Java 中常见的受检异常,表示在进行输入/输出操作(例如文件操作、网络通信)时发生了错误。
常见子类:

  • FileNotFoundException:文件未找到。
  • EOFException:文件意外结束。

示例代码:

import java.io.*;

public class IOExceptionExample {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("nonexistentfile.txt");
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到:" + e.getMessage());
        }
    }
}
(2)FileNotFoundException

描述:
FileNotFoundExceptionIOException 的一个子类,表示试图打开一个不存在的文件或文件不可访问。

示例代码:

try {
    FileInputStream file = new FileInputStream("nonexistentfile.txt");
} catch (FileNotFoundException e) {
    System.out.println("文件未找到:" + e.getMessage());
}
(3)SQLException

描述:
SQLException 表示在执行 SQL 操作(例如查询、更新)时发生的错误。通常出现在数据库连接失败、SQL 语法错误、或操作无效时。

示例代码:

import java.sql.*;

public class SQLExceptionExample {
    public static void main(String[] args) {
        try {
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root", "password");
            Statement statement = connection.createStatement();
            statement.executeQuery("INVALID SQL QUERY"); // 抛出 SQLException
        } catch (SQLException e) {
            System.out.println("SQL 异常:" + e.getMessage());
        }
    }
}
(4)ClassNotFoundException

描述:
ClassNotFoundException 表示当 Java 程序试图加载一个类,而该类的定义不存在时抛出。通常出现在动态加载类的场景(如使用反射)。

示例代码:

try {
    Class.forName("com.nonexistent.ClassName");
} catch (ClassNotFoundException e) {
    System.out.println("类未找到:" + e.getMessage());
}
(5)InterruptedException

描述:
InterruptedException 表示线程在阻塞状态或等待过程中被中断时抛出。

示例代码:

public class InterruptedExceptionExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                System.out.println("线程被中断:" + e.getMessage());
            }
        });
        thread.start();
        thread.interrupt(); // 中断线程
    }
}

3. 错误(Error)

(1)OutOfMemoryError

描述:
当 JVM 无法为对象分配足够的内存时抛出。通常是由于内存泄漏或分配的对象过大导致。

示例代码:

public class OutOfMemoryErrorExample {
    public static void main(String[] args) {
        try {
            int[] largeArray = new int[Integer.MAX_VALUE];
        } catch (OutOfMemoryError e) {
            System.out.println("内存不足:" + e.getMessage());
        }
    }
}
(2)StackOverflowError

描述:
当方法递归调用过深,导致栈空间耗尽时抛出。

示例代码:

public class StackOverflowErrorExample {
    public static void recursiveMethod() {
        recursiveMethod(); // 无限递归
    }
    public static void main(String[] args) {
        recursiveMethod();
    }
}
(3)NoClassDefFoundError

描述:
当 JVM 无法加载某个类(可能是类定义丢失或类文件损坏)时抛出。

示例代码:

// 编译时存在的类,运行时被删除或损坏。

四、总结

Java 的异常体系具有层次化的结构,覆盖了从轻微的逻辑错误到系统级错误的各种情况。开发者应根据不同异常类型采取适当的处理策略:

  • 运行时异常: 应避免逻辑错误,通过良好的编码实践减少发生可能。
  • 受检异常: 必须捕获或声明抛出,保证程序在非正常情况下的稳定性。
  • 错误: 通常不可恢复,尽量避免导致错误的场景。

通过理解常见异常的特点和使用场景,可以显著提升代码的健壮性和可维护性。

你可能感兴趣的:(服务器)