Checked and Unchecked Exceptions in Java

In the previous tutorial, we have familiarized 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 Exception
2. Unchecked Exception
List of Checked and Unchecked Exception in Java

Checked Exception in Java


Checked exceptions are those exceptions that are checked by the java compiler itself 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.

Checked exceptions must be handled either by using try and catch block or by using 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. Exceptions always occur at runtime only. All the exceptions except RuntimeException, Error and their subclasses are called checked exceptions.


List of some important checked exceptions are given below:
1. ClassNotFoundException
2. InterruptedException
3. InstantiationException
4. IOException
5. SQLException
6. IllegalAccessException
7. FileNotFoundException, etc.

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

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

In the above 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 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.

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?
Program source code 2:

public class CheckedExceptionEx1 
{ 
public static void main(String[] args) 
{ 
 System.out.println("Hello Java"); 
try 
{ 
  Thread.sleep(1000); 
} 
catch (InterruptedException e) 
{ 
  e.printStackTrace(); 
  } 
 } 
}
Output: 
       Hello Java

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



Let’s take one more example program based on checked exceptions.
Program source code 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 
{ 
 File file = new File("not_existing_file.txt"); 
 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 code, there is no compilation error because we have handled 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 are those exceptions that are not checked by java compiler and occur during the runtime of a program. All exceptions under runtime exception class are called unchecked exceptions or runtime exceptions.

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 programmer does not handle it, JVM terminates program without the execution of rest of the code.

Some important examples of runtime exceptions are given below:
1. ArithmeticException
2. ClassCastException
3. NullPointerException
4. ArrayIndexOutOfBoundsException
5. NegativeArraySizeException
6. ArrayStoreException
7. IllegalThreadStateException
8. SecurityException, etc.

Let’s take an example program based on runtime exception.
Program source code 4:

public class UncheckedExceptionEx1 
{ 
public static void main(String[] args) 
{ 
 int x = 10; 
 int y = 0; 
 int z = x/y; 
 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, so it would throw ArithmeticException. This shows that runtime exceptions do not occur during compilation.

Let’s see one more example program based on unchecked exceptions.
Program source code 5:

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.

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

Program source code 6:

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 unchecked exception, Java compiler does not force to catch exception or to declare it in a throws clause.

5. Checked exceptions in java extends Exception class whereas, unchecked exceptions extends RuntimeException class.

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

Final words
Hope that this tutorial has covered a very important topic checked and unchecked exceptions in java with example programs. I hope that you will have understood all the important points related to checked and unchecked exceptions. 

Thanks for reading!!!
Next ⇒ Java Try Catch Block⇐ PrevNext ⇒

Leave a Comment