Introduction
IOException means any input-output exception that can occur while reading a file or writing into a file, basically accessing the file system. There can be many ways in which this exception can occur. The most common I/O exceptions are FileNotFoundException, InterruptedIOException, SocketException, UnsupportedDataTypeException.
What is Java I/O Exception?
Java IOException extends the Java Exception class. To get the Serializable form, the interface Serializable is implemented by the class that extends IOException. This is useful when you have custom exception classes for your project. For the program to exit gracefully in an exception case, we should surround it using try/catch block. This also means that IOException is a checked exception.
try {
FileInputStream fis = new FileInputStream("myfile.txt");
System.out.println("Check if the file is there... ");
} catch (IOException e) {
//e.printStackTrace();
System.out.println(e.getMessage());
}
Most IDEs will remind you to put the try/catch as soon as you use classes like FileInputStream, BufferedReader, DataInputStream, etc. Note that in the above program, though we have used IOException, we can also use a more specific FileNotFoundException (which is a subclass of IOException). However, IOException can handle other I/O errors as well. If we want, we can add both:
catch (FileNotFoundException fnp)
{
System.out.println("No such file found!");
}catch (IOException e) {
//e.printStackTrace();
System.out.println(e.getMessage());
}
This will not give an error, but the compiler will give you a warning, indicating that a more specific exception has already been handled. Note that the order is important here. If you first catch IOException, you will get an error while handling FileNotFoundException as it is redundant and can be handled by IOException itself. Note that we can also throw this exception as an ApplicationException, RuntimeException, or BusinessException to be handled by some other class:
throw new ApplicationException("Error in I/O operation", e);
In this case, we have to add the throws clause to the method as well:
public static void main(String[] args) throws ApplicationException
Conclusion
Java IOException is used to handle file-related errors like searching a file, reading it, or writing into it. It is a checked or compile-time exception that can be handled in the code by the developers.
There are many subclasses of IOException which can be used in the program instead of using the general IOException as well. IOException is a part of the java.io package and extends the java.lang.Exception class. IOExceptions can be handled using a try/catch block or by catching and then throwing the exception for some other class to handle.
People are also reading:
Leave a Comment on this Post