Checked exception and unchecked exception examples

In Java programming, for every occurrence of an exception, there generates an exception object, which holds all the details of the exception. Then the program searches for its respective exception handler. If found, the exception is handled or resolved, or else the program execution stops.

Java generates two types of exceptions. These are:

  1. Checked exception
  2. Unchecked exception

Difference Between Checked and Unchecked Exceptions in Java

Checked ExceptionUnchecked Exception
Checked exceptions occur at compile time. Unchecked exceptions occur at runtime.
The compiler checks a checked exception. The compiler does not check these types of exceptions.
These types of exceptions can be handled at the time of compilation. These types of exceptions cannot be a catch or handle at the time of compilation, because they get generated by the mistakes in the program.
They are the sub-class of the exception class. They are runtime exceptions and hence are not a part of the Exception class.
Here, the JVM needs the exception to catch and handle. Here, the JVM does not require the exception to catch and handle.
Examples of Checked exceptions:
  • File Not Found Exception
  • No Such Field Exception
  • Interrupted Exception
  • No Such Method Exception
  • Class Not Found Exception
Examples of Unchecked Exceptions:
  • No Such Element Exception
  • Undeclared Throwable Exception
  • Empty Stack Exception
  • Arithmetic Exception
  • Null Pointer Exception
  • Array Index Out of Bounds Exception
  • Security Exception

Checked exception and unchecked exception examples

Checked exceptions are those exceptions which are checked by compiler at the compile time. These exceptions will force you to either use try-catch or throws keywords. Checked exceptions include all exceptions except RuntimeException, their subclasses, and Error.

Examples: SQLException, IOExceptionetc.

import java.io.*; 
 
public class Main { 
	public static void main(String[] args) { 
		FileReader file = new FileReader("D:\\TestFiles\\file.txt"); 
		BufferedReader fileInput = new BufferedReader(file); 
 
		for (int i = 0; i < 5; i++) 
			System.out.println(fileInput.readLine()); 
 
		fileInput.close(); 
	} 
}

Output

Main.java:5: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
		FileReader file = new FileReader("D:\\TestFiles\\file.txt"); 
		                  ^
Main.java:9: error: unreported exception IOException; must be caught or declared to be thrown
			System.out.println(fileInput.readLine()); 
			                                     ^
Main.java:11: error: unreported exception IOException; must be caught or declared to be thrown
		fileInput.close(); 
		               ^
3 errors

Use throws keyword to throw the exception:

import java.io.*; 
 
public class Main { 
	public static void main(String[] args) throws IOException { 
		FileReader file = new FileReader("D:\\TestFiles\\file.txt"); 
		BufferedReader fileInput = new BufferedReader(file); 
 
		for (int i = 0; i < 5; i++) 
			System.out.println(fileInput.readLine()); 
 
		fileInput.close(); 
	} 
}

Output

Content file - line 1
Content file - line 2
Content file - line 3
Content file - line 4
Content file - line 5

Unchecked exceptions:

Unchecked exceptions represents those exceptional conditions which are not required be checked by compiler at the compile time. These are checked at run-time. These exceptions will not force you to either use try, catch or throws keyword. RuntimeException and their subclasses are unchecked exceptions. This Exception can be avoided by programmer.

Examples: ArithmeticException, NullPointerException etc.

public class Main { 
 
	public static void main(String[] args) 
	{ 
		int n1 = 15, n2 = 0; 
 
		// Try to divide by zero 
		try { 
			int result = n1 / n2; 
		} 
		catch (ArithmeticException e) { 
		    System.out.println("Exception in division operation");
		} 
	} 
}

Output

Exception in division operation

Use try catch block to handle the exception

public class Main { 
 
	public static void main(String[] args) 
	{ 
		int n1 = 15, n2 = 0; 
 
		// Try to divide by zero 
		try { 
			int result = n1 / n2; 
		} 
		catch (ArithmeticException e) { 
		    System.out.println("Exception in division operation");
		} 
	} 
}

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero 
        at Main.main(Main.java:8)

Note: Both Checked and Unchecked Exception can be handled by using keyword try, catch and finally keywords.

Difference Between checked and unchecked exceptions in java

Checked Exception Unchecked Exception
Checked Exceptions are those exceptions which are required to be handled at compile time. Unchecked Exceptions are those exceptions which are not required to be handled at compile time.
Checked Exception represents a direct subclass of Exception. Unchecked Exceptions represents the subclass of RuntimeException.
Examples:

Checked Exceptions : NoSuchMethod, ClassNotFound.

Examples:

Unchecked Exceptions : NullPointer, IndexOutOfBounds.

Java interview questions on Exception Handling

  • what is an exception?
  • How the exceptions are handled in java?
  • What is the difference between error and exception in java?
  • Can we keep other statements in between try catch and finally blocks?
  • Explain the exception hierarchy in java?
  • What are runtime exceptions in java?
  • What is outofmemoryerror in java?
  • What are checked and unchecked exceptions in java?
  • What is the difference between classnotfoundexception and noclassdeffounderror in java?
  • Will finally block get executed if return?
  • Can we throw an exception without throws?
  • What is rethrowing an exception in java?
  • What is the use of throws keyword in java?
  • What is exception propagation in java?
  • Difference between throw and throws in java?
  • What is finally in java?
  • What is the difference between final finally and finalize in java?
  • How to create customized exceptions in java?
  • What is classcastexception in java?
  • What is stackoverflowerror in java?
  • What is the superclass of all exception classes?
  • What is the use of printstacktrace method in java?
  • What is arraystoreexception in java?

Checked exception and unchecked exception examples

What is an example of a checked exception?

ClassNotFoundException, IOException, SQLException etc are the examples of the checked exceptions.

What is an unchecked exception?

An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.

Which of the following is an example of runtime unchecked exception?

The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

Is IOException is checked or unchecked?

Because IOException is a checked exception type, thrown instances of this exception must be handled in the method where they are thrown or be declared to be handled further up the method-call stack by appending a throws clause to each affected method's header.