How to Handle an IOException in Java?
Last Updated : 15 Feb, 2024
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:
- File not found.
- False user input.
- Bad URL for downloading files.
- File permission causes.
- 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"); } } }
OutputError 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.
Similar Reads
How to handle a java.lang.IndexOutOfBoundsException in Java? In Java programming, IndexOutOfBoundsException is a runtime exception. It may occur when trying to access an index that is out of the bounds of an array. IndexOutOfBoundsException is defined as the RuntimeException. It can be used to find the out-of-bound run-time errors of an array. It is a part of
2 min read
How to Handle SQLException in JDBC? Java Database Connectivity (JDBC) serves as the backbone for Java applications when interacting with databases. While establishing connections and executing queries, we developers often encounter SQLExceptions, which are inevitable in the real world. Handling those exceptions is crucial in the devel
4 min read
How to Handle Network Timeouts and Retries in Java? In Java, handling network timeouts and retries can be achieved the using different libraries and techniques. One common approach involved using built-in classes such as "HttpURLConnection" or external libraries such as Apache HttpClient. By setting appropriate timeouts and implementing the retry log
3 min read
How to Solve IllegalArgumentException in Java? An unexpected event occurring during the program execution is called an Exception. This can be caused due to several factors like invalid user input, network failure, memory limitations, trying to open a file that does not exist, etc. If an exception occurs, an Exception object is generated, contai
3 min read
How to Handle a java.lang.ArithmeticException in Java? In Java programming, the java.lang.ArithmeticException is an unchecked exception of arithmetic operations. This means you try to divisible by zero, which raises the runtime error. This error can be handled with the ArthmeticException. ArithmeticException can be defined as a runtime exception that ca
2 min read