Home >Java >javaTutorial >How is exception handling performed in Java I/O streams?
Java I/O streams may encounter exceptions, including IOException, FileNotFoundException, InvalidObjectException, and StreamCorruptedException. There are two ways to handle these exceptions: checked exceptions (which must be handled) and unchecked exceptions (which can be ignored). Handling exceptions using try-catch blocks ensures program robustness and data integrity. For example, code that reads a text file and writes it to another file uses a try-catch block to catch IOExceptions that may occur.
Java I/O streams are widely used for reading and writing files and their contents. Although they are powerful, you may encounter various anomalies when using them. Handling these exceptions is critical to ensuring program robustness and data integrity.
You may encounter the following types of exceptions when using I/O streams:
Java provides two main methods for handling I/O exceptions:
Checked exceptions: The code must handle these exceptions explicitly, otherwise the compiler will report an error. For example:
try { // 读取文件 } catch (IOException e) { // 处理异常 }
Unchecked exceptions: The code can ignore these exceptions without affecting the compiler. However, it is recommended to handle them to ensure application robustness. For example:
try { // 读取文件 } catch (RuntimeException e) { // 处理异常 }
Consider a program that reads a text file and writes it to another file. The following code uses a try-catch
block to handle exceptions that may occur:
import java.io.*; public class FileIO { public static void main(String[] args) { try { // 创建输入流读取文件 FileInputStream fis = new FileInputStream("input.txt"); // 创建输出流写入文件 FileOutputStream fos = new FileOutputStream("output.txt"); // 读写文件内容 int c; while ((c = fis.read()) != -1) { fos.write(c); } // 关闭流 fis.close(); fos.close(); } catch (IOException e) { // 打印异常信息 System.out.println("Error occurred: " + e.getMessage()); } } }
In this example, the try-catch
block handles any IOException
, print an exception message when an exception occurs.
The above is the detailed content of How is exception handling performed in Java I/O streams?. For more information, please follow other related articles on the PHP Chinese website!