常见的IOException子类及其使用场景:

IOException常用子类

EOFException

  • 场景:当期望从输入流中读取更多数据时,但已到达流的末尾。

  • 示例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    try (DataInputStream dis = new DataInputStream(new FileInputStream("file.txt"))) {
    while (true) {
    int data = dis.readInt();
    // Handle data...
    }
    } catch (EOFException e) {
    // End of file reached
    } catch (IOException e) {
    // Other IO error handling
    }

FileNotFoundException

  • 场景:尝试打开一个不存在的文件时。

  • 示例

    1
    2
    3
    4
    5
    6
    7
    try (BufferedReader br = new BufferedReader(new FileReader("nonexistentfile.txt"))) {
    // Read from the file
    } catch (FileNotFoundException e) {
    // File does not exist or cannot be opened
    } catch (IOException e) {
    // Other IO error handling
    }

SocketException

  • 场景:在网络通信中,当套接字出现错误时,例如 TCP 错误。

  • 示例

    1
    2
    3
    4
    5
    6
    7
    try (Socket socket = new Socket("example.com", 80)) {
    // Use the socket for communication
    } catch (SocketException e) {
    // Handle socket error
    } catch (IOException e) {
    // Other IO error handling
    }

UnknownHostException

  • 场景:当试图连接到一个未知的主机时。

  • 示例

    1
    2
    3
    4
    5
    6
    7
    8
    try {
    InetAddress address = InetAddress.getByName("unknownhost.com");
    // Use the InetAddress object
    } catch (UnknownHostException e) {
    // Handle unknown host
    } catch (IOException e) {
    // Other IO error handling
    }

InterruptedIOException

  • 场景:当IO操作被线程中断时。

  • 示例

    1
    2
    3
    4
    5
    6
    7
    try (InputStream in = new InterruptibleInputStream()) {
    // Perform IO operations that can be interrupted
    } catch (InterruptedIOException e) {
    // Handle interrupted IO
    } catch (IOException e) {
    // Other IO error handling
    }

UnsupportedEncodingException

  • 场景:当指定了一个不被支持的字符编码时。

  • 示例

    1
    2
    3
    4
    5
    6
    try {
    byte[] bytes = "example".getBytes("UTF-8");
    // Use the bytes
    } catch (UnsupportedEncodingException e) {
    // Handle unsupported encoding
    }