What is IOException in Java?

Posted in /  

What is IOException in Java?
ramyashankar

Ramya Shankar
Last updated on May 22, 2024

    Java is a general-purpose programming language used to develop various applications, websites, and embedded systems. While you write programs or develop applications using Java, you encounter exceptions or errors (in general language).

    An exception in computer programming is an event that occurs during the program execution and disrupts the normal flow of the program’s instructions.

    In Java, IOException is among the most common exceptions indicating errors in a program’s input and output operations. It can occur while reading or writing into a file, basically accessing the file system (files, directories, and streams).

    This blog post aims to explain IOException in Java with examples and its types and common causes.

    So, let us get started!

    What is IOException in Java?

    Exception Name

    IOException

    Exception Type

    Checked Exception

    Class

    java.io.IOException

    Other related Exceptions

    FileNotFoundException, EOFException, SocketException, InterruptedIOException, and FileLoadException

    IOException in Java is a checked exception that represents an error in input and output operations. It serves as the base class for those exceptions occurring when accessing a file, directory, or stream. It is part of the java.io package and the subclass of the Exception class.

    Checked exceptions are compile-time exceptions that programmers need to handle explicitly. They can be easily handled with a try-catch block .

    Another major category of exceptions in Java is unchecked or runtime exceptions. These exceptions do not need explicit handling. It entirely depends on programmers whether to handle unchecked exceptions explicitly or not.

    Some common subclasses of IOException in Java are FileNotFoundException, InterruptedIOException, SocketException, UnsupportedDataTypeException, etc.

    Syntax of Java IOException

    The following is the basic syntax of how to handle a Java IOException:

    try {
    //a block od code causing IOException
    } catch (IOException e) {
    //handling IOException
    }

    Causes of Java IOException

    The following are some common causes of IOException in Java:

    • File or directory not found.
    • Incorrect file permissions.
    • Disk full or write-protected.
    • The failure of a network of an I/O device.
    • Invalid user input.
    • Malfunctioned URL and URI .

    Constructors of IOException

    IOException()

    Constructs an IOException with null as its error detail message.

    IOException(String message)

    Constructs an IOException with a specified detail message.

    IOException(String message, Throwable cause)

    Constructs an IOException with a specified detail message and cause.

    IOException(Throwable cause)

    Constructs an IOException with a specified cause and a message – (cause==null ? null : cause.toString())

    Example

    When you try to read a file that does not exist, the Java compiler throws an IOException.

    Example

    import java.io.*;
    public class Example
    {
    public static void main(String[] args) 
    {
    FileReader f1 = new FileReader("file.txt");
    System.out.println(f1.read()); 
    f1.close();
    }
    }

    Output

    The file name is “Example”. Ensure to use the class name the same as the file name.

    Compile the program file using the “javac [filename]”. As IOException is a compile-time error, you get errors immediately after you compile it.

    javac Example.java

    Example.java:6: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
    FileReader f1 = new FileReader("file.txt");
    ^
    Example.java:8: error: unreported exception IOException; must be caught or declared to be thrown
    System.out.println(f1.read());
    ^
    Example.java:10: error: unreported exception IOException; must be caught or declared to be thrown
    f1.close();
    ^
    3 errors

    Explanation

    FileReader is a class to read data from a file. When the FileReader object, f1, tries to read data from the file “file.txt”, which does not exist, we get unreported exceptions FileNotFoundException and IOException .

    How to Handle IOExceptions in Java?

    The best way to handle IOException in Java is to use a try-catch block.

    A try-catch block has a separate try block and a catch block.

    • The try block is used to enclose the code that might throw an exception. If an exception occurs at any line of code in this block, the remaining code in the block will not be executed.
    • The catch block handles exceptions. You need to declare the exception type as a parameter of the catch block. Ensure to write the parent class of the encountered exception. For instance, in the above example, we have encountered FileNotFoundException, whose parent class is IOException.

    Syntax

    try{ 
    //code that can cause an exception 
    }catch(Exception_class_name ref)

    Remember to use the catch block after the try block. A single try block can have multiple catch blocks.

    Here is a solution for the above IOException, FileNotFoundException.

    Solution for FileNotFoundException

    We will use a simple try-catch block to handle the unreported exceptions we encountered in the above example.

    import java.io.*;
    public class Example
    {
    public static void main(String[] args) 
    {
    try{
    FileReader f1 = new FileReader("file.txt");
    System.out.println(f1.read()); 
    f1.close();
    }
    catch(IOException ie) { 
    System.out.println("An error occurred: " +ie.getMessage());
    }
    }
    }

    Output

    An error occurred: file.txt (No such file or directory)

    We have successfully handled FileNotFoundException and IOException using a try-catch block.

    Java IOException Examples

    Here are some common examples to explain how IOException occurs.

    1. Downloading a File With an Incorrect URL

    Example

    import java.io.*;
    import java.net.*;
    public class HelloWorld
    {
    public static void main(String[] args)
    {
    URL u1 =new URL("http://helloworld21.com/file.txt"); 
    InputStream in = u1.openStream();
    }
    }

    Output

    Compile the program file using javac followed by the file name.

    HelloWorld.java:8: error: unreported exception MalformedURLException; must be caught or declared to be thrown
    URL u1 =new URL("http://helloworld21.com/file.txt");
    ^
    HelloWorld.java:10: error: unreported exception IOException; must be caught or declared to be thrown
    InputStream in = u1.openStream();
    ^
    2 errors

    Explanation

    Here, we encountered unreported exceptions MalformedURLException and IOException.

    The program creates the URL object, u1, representing the URL http://helloworld21.com/file.txt . The InputStream in enables reading of the resource located at the specified URL. However, due to an incorrect URL, the Java compiler throws MalformedURLException.

    Solution

    The solution is the same, i.e., using the try-catch block to catch the exception.

    import java.io.*;
    import java.net.*;
    public class HelloWorld
    {
    public static void main(String[] args)
    {
    try{
    URL u1 =new URL("http://helloworld21.com/file.txt");
    InputStream in = u1.openStream();
    }
    catch(IOException ie){
    System.out.println("An error occurred: " +ie.getMessage());
    }
    }
    }

    Output

    An error occurred: helloworld21.com

    The program with a try-catch block executes successfully without any error or exception.

    2. Encoding the String Using an Invalid Format

    Example

    import java.io.*;
    public class Main {
    public static void main(String[] args) throws Exception {
    String str = "TechGeekBuzz";
    byte[] programming;
    //We are encoding the string using invalid format. 
    //It results in UnsupportedEncodingException. 
    programming = str.getBytes("Techies World for Tech Geeks");
    }
    }

    Output

    Exception in thread "main" java.io.UnsupportedEncodingException: Techies World for Tech Geeks
    at java.base/java.lang.StringCoding.encode(StringCoding.java:427)
    at java.base/java.lang.String.getBytes(String.java:941)
    at Main.main(Main.java:8)

    Explanation

    In the above example, we have encoded the given string using an unsupported encoding format, i.e., Bytes. Hence, we get UnsupportedEncodingException.

    Solution

    import java.io.*;
    public class Main {
    public static void main(String[] args) throws Exception {
    try{
    String str = "TechGeekBuzz";
    byte[] programming;
    //We are encoding the string using invalid format. 
    //It results in UnsupportedEncodingException. 
    programming = str.getBytes("Techies World for Tech Geeks");
    }
    catch(IOException ie)
    {
    System.out.println("An error occurred - " +ie.getMessage());
    }
    }
    }

    Output

    An error occurred - Techies World for Tech Geeks

    Types of IOException in Java

    Let us now discuss some common types of IOException in Java.

    • FileNotFoundException: It occurs when you access a file that does not exist.
    • SocketException: When there is an error in an underlying network protocol, you encounter SocketException.
    • EOFException: When the end of the file is reached unexpectedly, you get EOFException.
    • InterruptedIOException: You get this exception when your I/O operation is interrupted.
    • FileLoadException: When the file you want to access is available but cannot be loaded, you receive FileLoadException.
    • DirectoryNotFoundException: When you try to access a directory that does not exist, you receive DirectoryNotFoundException.
    • UnsupportedEncodingException: You encounter this exception when working with character encoding. Character encoding is the process of representing information in binary format.

    Conclusion

    This was all about IOException in Java. It occurs when dealing with input/output operations, such as reading or writing data to files, directories, and streams. It is a checked exception or compile-time exception that a programmer needs to handle explicitly. IOException serves as the base class for many other subclasses, including FileNotFoundException, FileLoadException, and UnsupportedEncodingException.

    The best solution to handle this exception is using a try-catch block. Enclose the code block that causes IOException in the try block. The catch block will handle the exception.

    If you have any doubts regarding this article, feel free to ask queries in the comments.

    People are also reading:

    FAQs


    When you read a particular file or access the file using the wrong path, you get the Java IOException. It is a checked exception that takes place during the compilation of Java programs.

    There are two ways to handle Java IOExceptions: 1. Using good programming while writing programs 2. Using the try-catch block to avoid any kind of exceptions in a program.

    While exceptions take place either at a compile time or runtime, IOExceptions take place only at the compile time.

    Both an error and an exception are the subclasses of the throwable class. While an error is a problem that takes place due to the shortage of system resources, an exception takes place at the runtime or compile time.

    Checked and unchecked are the two types of exceptions in Java.

    Leave a Comment on this Post

    0 Comments