Open In App

How to Handle an IOException in Java?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

An IOException in Java occurs when we try to perform some input or output tasks and then some issues occur. Programmers need to handle this issue explicitly with a piece of code that executes when an issue occurs. There is an entire class for handling such issues known as the IOException class, which falls under the Java.io package.

Reasons Occurring IOException

Some common reasons why IOException takes place are:

  1. File not found.
  2. False user input.
  3. Bad URL for downloading files.
  4. File permission causes.
  5. Input/Output device issues.

Example:

Java




// Java code to illustrate IOException
import java.io.*;
  
// Driver Class
public class Main {
    // Main Function
    public static void main(String[] args) throws IOException
    {
        // FileReader object
        FileReader file = new FileReader("file.txt");
  
        // Trying to read a file that doesn't exists
        System.out.println(file.read());
    }
}


Output:

Exception in thread "main" java.io.FileNotFoundException: file.txt (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112)
at java.base/java.io.FileReader.<init>(FileReader.java:60)
at Main.main(Main.java:12)

How to Handle IOException?

IOExceptions can be handled explicitly using try-catch and finally blocks. The code that may contain an exception must be written inside the try block; code handling exceptions should be written inside the catch block; and finally, the block contains the piece of code that must be executed irrespective of the occurrence of any issue. Note that use of final block is not a must, It must be used as per the requirement, while try-catch block are must. There can be one try block having multiple catch blocks as well. Now, let us discuss the syntax for using these blocks.

Syntax: IOException can be handelled using try-catch and finally blocks. The basic syntax for using these blocks is:

try{
// Code where Exception may occur
}

catch(Exception e){
// Piece of code to handle issue
}

finally{
// Code that must be execute no matter issue occurred or not
}

Example:

Java




// Java code to illustrate IOException
import java.io.*;
  
// Driver Class
public class Main {
    // Main Function
    public static void main(String[] args) throws IOException
    {
        // Code that may contain exception must be written
        // inside try block
        try {
            // FileReader object
            FileReader file = new FileReader("file.txt");
  
            // Trying to read a file that doesn't exists
            System.out.println(file.read());
        }
        
        // Code to handle exception must be inside catch
        // block
        catch (Exception exp) {
            // Piece of code to handle issue
  
            // Printing error
            System.out.println("Error occured: "
                               + exp.getMessage());
        }
        
        // Code that must be executed always
        finally {
            // Code that must be executed
            System.out.println(
                "Finally block will always executed, irrespective of occurence of issue");
        }
    }
}


Output

Error occured: file.txt (No such file or directory)
Finally block will always executed, irrespective of occurence of issue


Explanation of the above Program:

In previous code, when we were trying to open a file which didn’t exist, we got an error that was automatically handled by the IOException class (as we used the throws keyword along with the IOException class). But in this code, we tried to handle the exception explicitly by catching it. The try block contains the same code that we wrote to read a file previously. This time, when an issue occurred, the flow of the programme went inside the catch block, where code could be written to handle that exception. Along with this, using the finally block is not necessary; we can use it as per the requirement. The final block executes always, whether the issue occurs or not. Same, in this code, a file not found exception occurs, then code inside the catch block is executed, and at last, the code present inside the final block is executed.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads