Three Types of Exceptions in Java

In this article, we will look at the three basic categories of exceptions with examples.

The Three Kinds of Exceptions

  1. Checked Exception or Compile Time Exception
  2. Error
  3. Un-Checked Exception or Runtime Exception

Checked Exception or Compile Time Exception

The first kind of exception is the checked exception. These are exceptional conditions that a well-written application should anticipate and recover from. 
The checked exceptions are checked at compile time.  If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.

Checked Exception Example

Let's consider the following Java program that opens the file at location “C:\test\a.txt” and prints the first three lines of it. The program doesn’t compile, because the function main() uses FileReader() and BufferedReader() throws a checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also throw checked exception IOException.
import java.io.*;
 
class Main {
    public static void main(String[] args) {
        FileReader file = new FileReader("C:\\test\\a.txt");
        BufferedReader fileInput = new BufferedReader(file);
         
        // Print first 3 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 3; counter++) 
            System.out.println(fileInput.readLine());
         
        fileInput.close();
    }
}
Output:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - 
unreported exception java.io.FileNotFoundException; must be caught or declared to be 
thrown
 at Main.main(Main.java:5)
To fix the above program, we either need to specify a list of exceptions using throws, or we need to use a try-catch block. We have used throws in the below program. Since FileNotFoundException is a subclass of IOException, we can just specify IOException in the throws list and make the above program compiler-error-free.
import java.io.*;
 
class Main {
    public static void main(String[] args) throws IOException {
        FileReader file = new FileReader("C:\\test\\a.txt");
        BufferedReader fileInput = new BufferedReader(file);
         
        // Print first 3 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 3; counter++) 
            System.out.println(fileInput.readLine());
         
        fileInput.close();
    }
}

Error

The second kind of exception is the error. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.
When a dynamic linking failure or other hard failures in the Java virtual machine occurs, the virtual machine throws an Error. Simple programs typically do not catch or throw Errors.
Java library provides different built-in Error classes to handle or report error conditions.
VirtualMachineError
UnknownError
OutOfMemoryError
StackOverflowError

Un-Checked Exception or Runtime Exception

The third kind of exception is the runtime exception. These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API.
Consider following Java program. It compiles fine, but it throws ArithmeticException when run. The compiler allows it to compile because ArithmeticException is an unchecked exception.
public class Arithmetic {

 public static void main(String[] args) {

  try {
   int result = 30 / 0; // Trying to divide by zero
  } catch (ArithmeticException e) {
   System.out.println("ArithmeticException caught!");
  }
 }
}
Output:
java.lang.ArithmeticException: / by zero
 at com.javaguides.exceptions.exceptiondemo.Arithmetic.main(Arithmetic.java:11)
Let's consider NullPointerException is another best example for runtime exception. In below example, Person class object is not created using the new keyword but it is just declared with a null value. Now we are trying to access personName field value on null reference so JVM will throw NullPointerException exception here.
public class NullPointerExceptionExample {

    public static void main(String[] args) {

        Person personObj = null;

        try {
            String name = personObj.personName; // Accessing the field of a null object
            personObj.personName = "Jon Doe"; // Modifying the field of a null object
        } catch (NullPointerException e) {
            System.err.println("NullPointerException caught!");
        }

    }
}

class Person {

    public String personName;

    public String getPersonName() {
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }

}
Output:
NullPointerException caught!

Exception Handling Related Posts

Comments