MST

星途 面试题库

面试题:Java中处理输入输出流异常的常见方式有哪些

在Java输入输出流操作时,可能会遇到各种异常,如`IOException`等。请详细阐述至少两种处理这些异常的常见方式,并给出相应的代码示例。
15.8万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

1. 使用try-catch块捕获异常

通过try-catch块来捕获可能抛出的IOException,并在catch块中进行相应的处理。

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ExceptionHandlingExample1 {
    public static void main(String[] args) {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream("example.txt");
            int data;
            while ((data = inputStream.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            System.out.println("读取文件时发生错误: " + e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    System.out.println("关闭流时发生错误: " + e.getMessage());
                }
            }
        }
    }
}

2. 抛出异常

在方法签名中声明抛出IOException,让调用该方法的上层代码来处理异常。

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ExceptionHandlingExample2 {
    public static void readFile() throws IOException {
        InputStream inputStream = new FileInputStream("example.txt");
        int data;
        while ((data = inputStream.read()) != -1) {
            System.out.print((char) data);
        }
        inputStream.close();
    }

    public static void main(String[] args) {
        try {
            readFile();
        } catch (IOException e) {
            System.out.println("读取文件时发生错误: " + e.getMessage());
        }
    }
}