×

Search anything:

Types of Exceptions in Java

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

Reading time: 20 minutes | Coding time: 10 minutes

In this article, we have discussed the major types of Java Exceptions with concrete examples. There are mainly two types of exceptions in Java:

  • Checked exceptions
  • Unchecked exceptions

Classification of Java Exceptions by definition is as follows:

  • Build-in exceptions
  • Used defined exceptions

Each type can have different types of exceptions like SQLException, IOException, InvocationTargetException, and ClassNotFoundException.

We discuss them at length below. Before going into it, we will go through some basics of Exceptions in Java.

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

Java provides support for exception handling, making it easier for programmers to prevent unwanted bugs from wreaking havoc. Exceptions are handled using the java.lang.Exception class, which is a subclass of java.lang.Throwable. Throwable is the super class of all Java exceptions and errors. This hierarchy is illustrated below:

Java-Exceptions

Errors, unlike exceptions, are abnormal conditions that cannot be handled by Java programs. They are mainly caused by the environment in which application is running. Here are some examples of that:

  • JVM runs out of memory - OutOfMemoryError
  • Stack overflows - StackOverflowError

Checked Exceptions

Checked exceptions (aka compile-time exceptions) are checked by the compiler during compilation, confirming 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.

Example:

import java.io.*;
class CheckedException {
    public static void main(String args[]) {
        FileInputStream input1 = null;
        input1 = new FileInputStream("D:/file.txt");
        //file.txt does not exist at the location
        int m;
        while(( m = input1.read() ) != -1) {
            System.out.print((char)m);
        }
        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

We have three checked exceptions raised. A FileNotFoundException is raised when we try to create a new FileInputStream object with a file that does not exist. Then, IO Exceptions are raised when we try to read() and close() this non-existent file.

Other checked exceptions:

  • SQLException - raised when querying databases, syntax errors
  • ClassNotFoundException - JVM cannot find a specified class
  • InvocationTargetException - wraps an exception thrown by an invoked method

Unchecked Exceptions

Unchecked exceptions (aka run-time exceptions) are those exceptions that occur during the execution of the program. They are not checked while compiling the program. For example, programming bugs like logical errors, or using incorrect APIs.

There are extremely common exceptions. After all, as a wise programmer once said:

At the source of every error which is blamed on the computer you will find at least two human errors, including the error of blaming it on the computer. - Anonymous Programmer

Here is an example that will illustrate what these logical errors could be:

Example:

import java.io.*;
class UncheckedException {
   public static void main(String args[]) {
      int num[] = {1, 2, 3, 4};
      System.out.println(num[5]);
      int p = Integer.parseInt ("foo") ;
      int q = 0;
      int result = num[1]/q;
      System.out.println(result);
   }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4
Exception in thread "main" java.lang.NumberFormatException: For input string: "foo"
Exception in thread "main" java.lang.ArithmeticException: / by zero  

We have three unchecked exceptions raised. An ArrayIndexOutOfBounds is raised when we try to access an element at the 5th position in an array of 4 numbers. Then, a NumberFormatException is raised when we try to input a string to Integer.parseInt(). Finally, an ArithmenticException is raised when we perform an incorrect arithmetic operation, such as dividing a number by zero.

Other unchecked exceptions:

  • IllegalStateException - the state of the environment does not match the operation being executed
  • NullPointerException - accessing an object with a reference variable whose current value is null (or empty)
  • IllegalArgumentException - incorrect argument is passed to a method

Classification of Java Exceptions by definition:

Built-in Exceptions

Built-in exceptions are readily available in Java libraries. Below is a list of some important built-in exceptions in Java. Notice that it includes all exceptions mentioned in the examples thus far:

  • ArithmeticException- an exceptional condition has occurred in an arithmetic operation.
  • ArrayIndexOutOfBoundsException- indicates that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
  • ClassNotFoundException- accessing a class whose definition is not found
  • FileNotFoundException- file is not accessible or does not open
  • IOException- an input-output operation failed or interrupted
  • InterruptedException- a thread is waiting , sleeping , or doing some processing, and it is interrupted
  • NoSuchFieldException- a class does not contain the field (or variable) specified
  • NoSuchMethodException- accessing a method which is not found
  • NullPointerException- referring to the members of a null object
  • NumberFormatException- the method could not convert a string into a numeric format
  • RuntimeException- This represents any exception which occurs during runtime
  • StringIndexOutOfBoundsException- It is thrown by String class methods to indicate that an index is either negative than the size of the string

User-defined Exceptions

Built-in exceptions are useful in handling frequent errors that occur, but they do not describe specific scenarios that you would come across as a programmer. Sometimes, you need custom exceptions for these situations. These are user-defined exceptions. To define a custom exception, the user has to create their own class as a subclass of the Exception class. This is because since exceptions inherit from java.lang.Exception.

Further Reading

Learn how to create user-defined exceptions here
Read about how each type of exception can be handled by the programmer here

Test yourself to see how well you understood the types of exceptions in Java.

Go through this sample code:

import java.util.Scanner;
public class SampleException {
    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");
        }
    }
}

With input:

Enter your age in Numbers: Twelve

Test Yourself

In the above code, how many checked and unchecked exceptions will be raised, respectively?

None, 1
3, None
2, 3
1, 2
A java.util.InputMismatchException is thrown at runtime. There are no checked exceptions in this code. This exception is thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

With this article at OpenGenus, we must have a good idea of the different types of Exceptions in Java. Enjoy.

Types of Exceptions in Java
Share this