Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll learn about Java errors and exceptions and their differences.

2. The Throwable Class

Error and Exception are both subclasses of the Throwable class and are used to indicate that an abnormal situation has happened. Furthermore, only instances of Throwable and its subclasses can be thrown by the Java Virtual Machine or caught in a catch clause.

Instances of Error and Exception are created to include information about the situation (for example, the stack trace):

Throwable

3. Error

Errors indicate abnormal situations that should never happen. An error is thrown when a serious problem has occurred. Further, errors are regarded as unchecked exceptions, and applications should not try to catch and handle them. Moreover, errors happen at run time and cannot be recovered.

Now let’s see an example:

public class ErrorExample {
    
    public static void main(String[] args) {
        throw new AssertionError();
    }

}

If we run the above code, we get the following:

Exception in thread "main" java.lang.AssertionError:
at com.baeldung.exception.exceptions_vs_errors.ErrorExample.main(ErrorExample.java:6)

The code caused an error called the AssertionError, which is thrown to indicate when an assertion has failed.

Other examples of Java errors include StackOverflowError, LinkageError, IOError, and VirtualMachineError.

4. Exception

Exceptions are abnormal conditions that applications might want to catch and handle. Exceptions can be recovered using a try-catch block and can happen at both run time and compile time.

Some of the techniques used for exception handling are try-catch block, throws keyword, and try-with-resources block.

Exceptions are divided into two categories: Runtime Exceptions and Checked Exceptions.

4.1. Runtime Exceptions

RuntimeException and its subclasses are the exceptions that can be thrown while the Java Virtual Machine is running. Further, they are unchecked exceptions. Unchecked exceptions don’t need to be declared in the method signature using the throws keyword if they can be thrown once the method is executed and propagate outside the method’s scope.

Let’s see an example:

public class RuntimeExceptionExample {
    public static void main(String[] args) {
        int[] arr = new int[20];

        arr[20] = 20;

        System.out.println(arr[20]);
    }
}

After we run the above code, we get the following:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
  at com.baeldung.exception.exceptions_vs_errors.RuntimeExceptionExample.main(RuntimeExceptionExample.java:7)

As we can see, we got an ArrayIndexOutOfBoundsException which is a subclass of IndexOutOfBoundsExceptionwhich is itself a subclass of RuntimeException.

Other subclasses of RuntimeException include IllegalArgumentExceptionNullPointerException, and ArithmeticException.

4.2. Checked Exceptions

Other exceptions that are not subclasses of RuntimeException are checked exceptions. They need to be declared in the method signature using the throws keyword if they can be thrown once the method is executed and propagate outside the method’s scope:

public class CheckedExceptionExcample {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream(new File("test.txt"))) {
            fis.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

If we run the above code, we get the following:

java.io.FileNotFoundException: test.txt (No such file or directory)
  at java.io.FileInputStream.open0(Native Method)
  at java.io.FileInputStream.open(FileInputStream.java:195)
  at java.io.FileInputStream.<init>(FileInputStream.java:138)
  at com.baeldung.exception.exceptions_vs_errors.CheckedExceptionExcample.main(CheckedExceptionExcample.java:9)

We got a FileNotFoundException which is a subclass of IOException, which is a subclass of Exception.

TimeoutException and SQLException are other examples of checked exceptions.

5. Conclusion

In this article, we learned the differences between errors and exceptions in the Java ecosystem.

As always, the complete code samples are available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.