Types of Exceptions in Java

Sagar Arora Developer Tips, Tricks & Resources

 Java is an object-oriented programming language. It provides support for various mechanisms such as exception handling. This feature of Java enables developers to manage the runtime errors caused by the exceptions.

In this article, you will learn about exceptions in Java. You will also learn about different types of exceptions in Java.

Exceptions are the unwanted errors or bugs or events that restrict the normal execution of a program. Each time an exception occurs, program execution gets disrupted. An error message is displayed on the screen.

There are several reasons behind the occurrence of exceptions. These are some conditions where an exception occurs:

  • Whenever a user provides invalid data.
  • The file requested to be accessed does not exist in the system.
  • When the Java Virtual Machine (JVM) runs out of memory.
  • Network drops in the middle of communication.

Now let us explore different types of exceptions in Java.

The parent class of all the exception classes is the java.lang.Exception class. Figure 1 illustrates the different types of Java exceptions.

Figure 1: Types of Exceptions in Java

If we talk about the Exception class, it is a subclass of the built-in Throwable class. There is another subclass which is derived from the Throwable class i.e. Error as illustrated in Figure 1. The error can be defined as an abnormal condition that indicates something has gone wrong with the execution of the program. These are not handled by Java programs.

There are some important methods available in the Throwable class which are as follows:

  • public String getMessage() – Provides information about the exception that has occurred through a message, which is initialized in the Throwable constructor.
  • public Throwable getCause() – Provides root cause of the exception as represented by a Throwable object.
  • public void printStackTrace() – Used to display the output of toString() along with the stack trace to System.err (error output stream).
  • public StackTraceElement [] getStackTrace() – Returns an array with each element present on the stack trace. The index 0 element will symbolize the top of the call stack, and the last element of array will identify the bottom of the call stack.

There are mainly two types of exceptions in Java as follows:

  • Checked exception
  • Unchecked exception

Checked exception

Checked exceptions are also known as compile-time exceptions as these exceptions are checked by the compiler during the compilation process to confirm whether the exception is handled by the programmer or not. If not, then the system displays a compilation error. For example, SQLException, IOException, InvocationTargetException, and ClassNotFoundException.

To illustrate the concept of checked exception, let us consider the following code snippet:

import java.io.*;
class demo1 {
    public static void main(String args[]) {
        FileInputStream input1 = null;

        /* FileInputStream(File filename) is a constructor that will throw
         *     FileNotFoundException (a checked exception) 
         */

        input1 = new FileInputStream("D:/file.txt");
        int m;

        // The read() of FileInputStream will also throw a checked exception
        while(( m = input1.read() ) != -1) {
            System.out.print((char)m);
        }

        // The close() will close the file input stream, and it will also throw a exception
        input1.close();
    }
}

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException

throw keyword

It is clearly displayed in the output that the program throws exceptions during the compilation process. There are two methods of resolving such issues. You can declare the exception with the help of the throw keyword.

import java.io.*;
class demo1 {
    public static void main(String args[]) throws IOException {
        FileInputStream input1 = null;
        input1 = new FileInputStream("D:/file.txt");

        int m;
        while ((m = input1.read()) != -1) {
            System.out.print((char)m);
        }

        input1.close();
    }
}

Output: The file will be displayed on the screen.

try-catch block

Apart from the above-mentioned method, there is another way to resolve exceptions. You can manage them with the help of try-catch blocks.

import java.io.*;
class demo1 {
    public static void main(String args[]) {
        FileInputStream input1 = null;
        try {
            input1 = new FileInputStream("D:/file.txt");
        } catch(FileNotFoundException input2) {
            system.out.println("The file does not " + "exist at the location");
        }

        int m;
        try {
            while((m = input1.read()) != -1) {
                System.out.print((char)m);
            }

            input1.close();
        } catch(IOException input3) {
            system.out.println("I/O error occurred: "+ input3);
        }
    }
}

Output: The code will run smoothly and the file will be displayed.

Now, let us learn about other checked exceptions. Some of them are:

SQLException

This type of exception occurs while executing queries on a database related to the SQL syntax. For example, consider the following code snippet:

public void setClientInfo(String sname, String svalue) throws SQLClientInfoException {
    try {
        checkClosed();
        ((java.sql.Connection) this.mc).setClientInfo(sname, svalue);
    } catch (SQLException sqlEx) {
        try {
            checkAndFireConnectionError(sqlEx);
        } catch (SQLException sqlEx2) {
            SQLClientInfoException client_Ex = new SQLClientInfoException();
            client_Ex.initCause(sqlEx2);
            throw client_Ex;
        }
    }
}

Output: This code will generate a SQLException.


Stackify Loves Developers

IOException

This type of exception occurs while using file I/O stream operations. For example, consider the following code snippet:

import java.io.*;
public class sample_IOException {
    private static String filepath = "D:\User\guest\Desktop\File2.txt";

    public static void main(String[] args) {
        BufferedReader br1 = null;
        String curline;

        try {
            br1 = new BufferedReader(new FileReader(filepath));

            while ((curline = br1.readLine()) != null) {
                System.out.println(curline);
            }
        } catch (IOException e) {
            System.err.println("IOException found :" + e.getMessage());
        } finally {
            try {
                if (br1 != null)
                    br1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Output: This code will generate an IOException.

ClassNotFoundException

This type of exception is thrown when the JVM is not able to find the required class. It may be due to a command-line error, a classpath issue, or a missing .class file. For example, consider the following code snippet:

public class sample_ClassNotFoundException {
    private static final String CLASS_TO_LOAD = "main.java.Utils";

    public static void main(String[] args) {
        try {
            Class loadedClass = Class.forName(CLASS_TO_LOAD);
            System.out.println("Class " + loadedClass + " found!");
        } catch (ClassNotFoundException ex) {
            System.err.println("ClassNotFoundException was found: " + ex.getMessage());
            ex.printStackTrace();
        }
    }
}

Output: This code will generate a ClassNotFoundException.

InvocationTargetException

This type of exception wraps an exception thrown by an invoked method or a constructor. The thrown exception can be accessed with the help of the getTargetException method. For example, consider the following code snippet:

package main.samplejava;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Example {
    @SuppressWarnings("unused")
    private int test_sample(String s1) {
        if (s1.length() == 0)
            throw new IllegalArgumentException("The string should have at least one character!");
        System.out.println("Inside test_sample: argument's value equals to: "" + s1 + """);
        return 0;
    }

    public static void main(String... args) {
        try {
            Class<?> c1 = Class.forName("main.samplejava. Example");
            Object t1 = c1.newInstance();
            Method[] declared_Methods = c1.getDeclaredMethods();
            for (Method method : declared_Methods) {
                String methodName = method.getName();
                if (methodName.contains("main"))
                    continue;

                System.out.format("Invoking %s()%n", methodName);

                try {
                    method.setAccessible(true);
                    Object returnValue = method.invoke(t1, "");
                    System.out.format("%s() returned: %d%n", methodName, returnValue);
                } catch (InvocationTargetException ex) {
                    System.err.println("An InvocationTargetException was caught!");
                    Throwable cause = ex.getCause();
                    System.out.format("Invocation of %s failed because of: %s%n",
                        methodName, cause.getMessage());
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
            System.err.println("The following exception was thrown:");
            ex.printStackTrace();
        }
    }
}

Output:

Invoking testMethod()
An InvocationTargetException was caught!
Invocation of testMethod failed because of: The string must contain at least one character!

Output: This code will generate an InstantiationException.

Unchecked exception

The unchecked exceptions are those exceptions that occur during the execution of the program. Hence they are also referred to as Runtime exceptions. These exceptions are generally ignored during the compilation process. They are not checked while compiling the program. For example, programming bugs like logical errors, and using incorrect APIs.

To illustrate the concept of an unchecked exception, let us consider the following code snippet:

import java.util.Scanner;
public class Sample_RunTimeException {
    public static void main(String[] args) {
        // Reading user input
        Scanner input_dev = new Scanner(System.in);
        System.out.print("Enter your age in Numbers: ");
        int age1 = input_dev.nextInt();
        if (age1>20) {
            System.out.println("You can view the page");
        } else {
            System.out.println("You cannot view the page");
        }
    }
}

Output 1:

Enter your age in Numbers: 21
You can view the page

Output 2:

Enter your age in Numbers: Twelve
Exception in thread “main” java.util.InputMismatchException
at java.util.Scanner.throwFor (Unknown Source)
at java.util.Scanner.next (Unknown Source)
at java.util.Scanner.nextInt (Unknown Source)
at java.util.Scanner.nextInt (Unknown Source)
at exceptiondemo.sample_runtimedemo.main(Sample_RunTimeExceptionDemo.java:11)

Now, let us learn about other unchecked exceptions. Some of them are:

NullPointerException

This type of exception occurs when you try to access an object with the help of a reference variable whose current value is null or empty. For example, consider the following code snippet:

// Program to demonstrate the NullPointerException
class SampleNullPointer {
    public static void main(String args[]) {
        try {
            String a1 = null; // null value
            System.out.println(a1.charAt(0));
        } catch(NullPointerException e) {
            System.out.println("NullPointerException is found in the program.");
        }
    }
}

Output: NullPointerException is found in the program.

ArrayIndexOutofBound

This type of exception occurs when you try to access an array with an invalid index value. The value you are providing is either negative or beyond the length of the array.

For example, consider the following code snippet:

// Program to demonstrate the ArrayIndexOutOfBoundException
class sample_ArrayIndexOutOfBound {
    public static void main(String args[]) {
        try {
            int b[] = new int[6];
            b[8] = 2; // we are trying to access 9th element in an array of size 7
        } catch(ArrayIndexOutOfBoundsException e) {
            System.out.println ("The array index is out of bound");
        }
    }
}

Output: The array index is out of bound

IllegalArgumentException

This type of exception occurs whenever an inappropriate or incorrect argument is passed to a method. For example, if a method is defined with non-empty string as parameters. But you are providing null input strings. Then, the IllegalArgumentException is thrown to indicate the user that you cannot pass a null input string to the method.

Consider the following code snippet to demonstrate this type of exception:

import java.io.File;
public class Sample_IllegalArgumentException {
    public static String createRelativePath(String par, String f_name) {
        if (par == null)
            throw new IllegalArgumentException("You cannot provide null parent path!");

        if (f_name == null)
            throw new IllegalArgumentException("Please enter the complete filename!");
        
        return par + File.separator + f_name;
    }

    public static void main(String[] args) {
        // This command will be successfully executed.
        system.out.println(IllegalArgumentExceptionExample.createRelativePath("dir1", "file1"));
        system.out.println();

        // This command will throw an IllegalArgumentException.
        System.out.println(IllegalArgumentExceptionExample.createRelativePath(null, "file1"));
    }
}

Output: This code will generate an IllegalArgumentException.

IllegalStateException

This type of exception occurs when the state of the environment does not match the operation being executed. For example, consider the following code snippet, which demonstrates this type of exception:

/**
 * This code will publish the current book.
 * If the book is already published, it will throw an IllegalStateException.
 **/
public void pub() throws IllegalStateException {
    Date pub_at = getPub_at();

    if (pub_at == null) {
        setPub_at(new Date());
        Logging.log(String.format("Published '%s' by %s.", getTitle(), getAuthor()));
    } else {
        throw new IllegalStateException(
        String.format("Cannot publish '%s' by %s (already published on %s).",
            getTitle(), getAuthor(), pub_at));
    }
}

Output: This code will generate IllegalStateException.

If a publication date already exists in the system, then it will produce an IllegalStateException that indicates that the book cannot be published again.


Stackify Loves Developers

NumberFormatException

This type of exception occurs when you pass a string to a method that cannot be converted to a number. For example, consider the following code snippet:

// Program to demonstrate the NumberFormatException
class Sample_NumberFormat {
    public static void main(String args[]) {
        try {
            // "Test" is not a number
            int n = Integer.parseInt ("Test") ;
            System.out.println(n);
        } catch(NumberFormatException e) {
            System.out.println("Number format exception");
        }
    }
}

Output: This code will generate NumberFormatException.

ArithmeticException

This type of exception occurs when you perform an incorrect arithmetic operation. For example, if you divide any number by zero, it will display such an exception. Let us consider the following code snippet:

// Program to demonstrate the ArithmeticException
class Sample_ArithmeticException {
    public static void main(String args[]) {
        try {
            int p = 30, q = 0;
            int r = p/q;  // It cannot be divided by zero
            System.out.println ("Result = " + r);
        } catch(ArithmeticException e) {
            System.out.println ("Number cannot be divided by 0");
        }
    }
}

Output: This code will generate an ArithmeticException.

Read next: 9 Best Practices to Handle Exceptions in Java

About Sagar Arora

Sagar Arora is an experienced technical content writer with knowledge of C, C++, python, PHP, Java languages. His writing coverage includes companies such as iSkysoft, Keepvid, Xpo2, Stackify, Entrepreneurbus, etc.
Improve Your Code with Retrace APM

Stackify’s APM tools are used by thousands of .NET, Java, and PHP developers all over the world.
Explore Retrace’s product features to learn more.