Checked and Unchecked Exceptions in Java

In this tutorial, we will learn checked and unchecked exceptions in Java with the help of example programs. We know that there are two types of exceptions in Java: first is predefined exceptions, and second user-defined exceptions.

The predefined exceptions are those exceptions that are already defined by the java system. All the predefined exceptions are further divided into two groups:

  1. Checked Exceptions
  2. Unchecked Exceptions
    List of Checked and Unchecked Exception in Java

Checked Exceptions in Java


Checked exceptions are those exceptions that are checked by the Java compiler itself at compilation time and are not under runtime exception class hierarchy. If a method throws a checked exception in a program, the method must either handle the exception or pass it to a caller method.

We must handle checked exceptions either by using try and catch block or by using a throws clause in the method declaration. If not handles properly, it will give a compile-time error.

Most people have confusion and say that checked exceptions occur at compile-time, that is wrong. All exceptions always occur at runtime only, but some exceptions are detected at compile-time and some other at runtime.

The exceptions that are checked by Java compiler at compilation time are called checked exceptions in Java. All the exceptions except RuntimeException, Error, and their subclasses are checked exceptions.


Note:

Compile-time errors are not exceptions. They come under errors. In Java, only runtime errors come under exceptions.

List of Checked Exceptions in Java


A list of some important checked exceptions is given below:

  • ClassNotFoundException
  • InterruptedException
  • InstantiationException
  • IOException
  • SQLException
  • IllegalAccessException
  • FileNotFoundException, etc

Let’s take an example program where we will pause the main thread for a specified amount of time and see what happens on the execution of the program.

Example 1:

package exceptionHandling; 
public class CheckedExceptionEx1 { 
public static void main(String[] args) 
{ 
   System.out.println("Hello Java"); 
// Here, the main thread paused for a specified amount of time.
   Thread.sleep(1000); // Compilation error. 
 } 
}
Output: 
      Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
      Unhandled exception type InterruptedException

In the above example code, there is a compilation error: “Unhandled exception type InterruptedException”. This is because thread.sleep(); method throws an InterruptedException that has been not handled by a try-catch or throws clause.

Since InterruptedException is a checked exception that is checked by the compiler itself for the smooth execution of the program at runtime, therefore, we got a compilation error at compile-time and InterruptedException exception at runtime.

Handle Checked Exception in Java


To avoid this compilation error, we will have to handle this checked exception either using a try-catch block or throws clause. Let’s handle it and see what will be the output?

Example 2:

public class CheckedExceptionEx1 { 
public static void main(String[] args) 
{ 
   System.out.println("Hello Java"); 
// Apply the try-catch block to handle checked exception.
   try 
   { 
     Thread.sleep(1000); 
   } 
   catch(InterruptedException e) 
   { 
     e.printStackTrace(); 
    } 
 } 
}
Output: 
       Hello Java

As you can see in the above example code, we have handled the checked exceptions by using a try-catch block. You can also use throws clause instead of the try-catch block.


Let’s take an example program in which we will handle Java checked exceptions using a throws clause.

Example 3:

package exceptionHandling; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
public class CheckedExceptionEx { 
public static void main(String[] args) throws FileNotFoundException 
{ 
// Creating a file object.
   File file = new File("not_existing_file.txt"); 

// Create an object of FileInputStream and pass the reference variable file to it.
   FileInputStream stream = new FileInputStream(file); 
 } 
}
Output: 
       Exception in thread "main" java.io.FileNotFoundException: not_existing_file.txt 
       (The system cannot find the file specified)

In the above example code, there is no compilation error because we have handled the checked exception by using throws clause. But, at runtime, FileNotFoundException exception occurs because we are trying to access a non-existing file.

Unchecked Exceptions (Runtime Exceptions) in Java


Unchecked exceptions in Java are those exceptions that are checked by JVM, not by java compiler. They occur during the runtime of a program. All exceptions under the runtime exception class are called unchecked exceptions or runtime exceptions in Java.

We can write a Java program and compile it. But we cannot see the effect of unchecked exceptions and errors until we run the program. This is because Java compiler allows us to write a Java program without handling unchecked exceptions and errors.

Java compiler does not check runtime exception at compile time whether programmer handles them or not. If a runtime exception occurs in a method and the programmer does not handle it, JVM terminates the program without the execution of rest of the code.

List of Unchecked Exceptions in Java


Some important examples of runtime exceptions are given below:

  • ArithmeticException
  • ClassCastException
  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • NegativeArraySizeException
  • ArrayStoreException
  • IllegalThreadStateException
  • SecurityException, etc.

Let’s take an example program based on Java runtime exception.

Example 4:

public class UncheckedExceptionEx1 { 
public static void main(String[ ] args) 
{ 
  int x = 10; 
  int y = 0; 
  int z = x/y; // runtime exception occurs.
  System.out.println(z); 
 } 
}
Output: 
   Exception in thread "main" java.lang.ArithmeticException: / by zero 
   at exceptionHandling.UncheckedExceptionEx1.main(UncheckedExceptionEx1.java:9)

You will have noticed that the above code has become compile successfully. But when you will go to execute it, then it will throw a runtime exception named ArithmeticException. This shows that runtime exceptions do not occur during compilation.

Handle Runtime Exception in Java


To avoid this runtime error, we will have to handle this unchecked exception either using a try-catch block or throws clause. Let’s handle it and see what will be the output?

Example 5:

public class HandleRuntimeException {
public static void main(String[] args) 
{
   int x = 10; 
   int y = 0; 
// Apply try-catch block to handle runtime exception.
   try {
     int z = x/y; // runtime exception.
     System.out.println(z);
   } catch(ArithmeticException ae) 
     {
       System.out.println("A number cannot be divided by zero");
     }
  }
}
Output:
      A number cannot be divided by zero

In this example, we have handled runtime exceptions by using a try-catch block and generated user friendly message on the console. We can also use a throws clause instead of the try-catch block to handle runtime exception.


Let’s consider one more example program based on unchecked exceptions.

Example 6:

public class UncheckedExceptionEx2 { 
public static void main(String[] args) 
{ 
   int x[ ] = {1, 2, 3, 4}; 
/* Here, an array contains only 4 elements, but we will try to * display the value of 6th element. 
   It should throw ArrayIndexOutOfBoundsException */ 
   System.out.println(x[6]); 
 } 
}
Output: 
      Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6

The above code would also compile successfully, but at runtime, we will get ArrayIndexOutOfBoundsException unchecked exception. This exception is thrown when an array element is accessed out of the index.

We can handle exception found in the above code by using try-catch block carefully. Using try-catch block, we can generate a user-friendly message so that we will be able to correct this issue. Let’s handle it.

Example 7:

public class UncheckedExceptionEx2 { 
public static void main(String[] args) 
{ 
 try 
 { 
    int x[ ] = {1, 2, 3, 4}; 
    System.out.println(x[6]); 
 } 
 catch(ArrayIndexOutOfBoundsException e)
 { 
    System.out.println("Specified index does not exist. " + "Please correct the error."); 
  } 
 }
}
Output: 
       Specified index does not exist. Please, correct the error.

Difference between Checked and Unchecked Exceptions in Java


There are many important differences between checked and unchecked exceptions in Java. They are as follows:

1. The classes that directly inherit Throwable class except RuntimeException and Error are called checked exceptions whereas, classes that directly inherit RuntimeException are called unchecked exceptions.

2. Checked exceptions are checked and handled at compile-time whereas, unchecked exceptions are not checked and handled at compile time. They are checked at runtime.

3. Examples of checked exceptions are IOException, SQLException, ClassNotFoundException, etc whereas, examples of unchecked exceptions are ArithmeticException, ClassCastException, NullPointerException, IllegalArgumentException, etc.

4. When a checked exception occurs in a method, the method must either catch the exception or pass exception to its caller method. But in the case of an unchecked exception, Java compiler does not force to catch exception or to declare it in a throws clause.

5. Checked exceptions in Java extend Exception class, whereas unchecked exceptions extend RuntimeException class.

6. A checked exception happens when there is a chance of a higher failure rate. whereas unchecked exceptions occur, mostly due to programming mistakes/errors.