Table of contents
1.
Introduction
2.
What is a Checked Exception in Java?
2.1.
Example
3.
What is an Unchecked Exception in Java?
3.1.
Example
4.
Differences between Checked and Unchecked Exceptions in Java
5.
Best Practices for Checked and Unchecked Exceptions in Java
6.
Frequently Asked Questions
6.1.
What is the difference between RuntimeException and exception in Java?
6.2.
What is the type of unchecked exception?
6.3.
How do unchecked exceptions affect program flow?
6.4.
Is ArithmeticException a checked or unchecked exception?
6.5.
Is NullPointerException checked or unchecked?
7.
Conclusion
Last Updated: Dec 6, 2024
Easy

Difference Between Checked and Unchecked Exception

Author Gunjan Batra
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java exception is an unexpected issue that arises while a program is running, causing it to deviate from its normal operation. These exceptions can disrupt the flow of the program and need to be handled properly to prevent crashes and ensure smooth execution. There are two types of exceptions: 

  1. Checked exceptions
  2. Unchecked exceptions
Difference Between Checked and Unchecked Exception

What is a Checked Exception in Java?

  • A checked exception is the one that the compiler checks or notifies during compilation.
  • Checked Exceptions are also known as compile-time exceptions.
  • These exceptions cannot be ignored.
  • If a code within a function throws a checked exception, the function must handle the exception or specify it using the throws keyword.

Example

A FileReader class is used in a file handling programme to read data from a file. If the file specified in its constructor does not exist, a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception.

Here, If the Name.txt file is not present in the specified location during the compilation, this code will throw an error.

import java.io.File;
import java.io.FileReader;

public class Test{

   public static void main(String args[]) {		
      File file = new File("E://Name.txt");
      FileReader fr = new FileReader(file); 
   }
}

 

Output: 

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Unhandled exception type FileNotFoundException

	at Test.main(Test.java:8)

What is an Unchecked Exception in Java?

  • An unchecked exception occurs during the execution process.
  • Unchecked Exceptions are also known as runtime exceptions.
  • Programming mistakes, such as logic errors or improper use of an API, are examples of this.
  • Runtime exceptions are ignored during compilation.

Example

If a 7-element array is declared and the programme attempts to access its 8th element, an ArrayIndexOutOfBoundsExceptionexception occurs.

Here, the below program will be successfully compiled, but it’ll throw an exception at runtime.

public class Test{

	public static void main(String args[]) {
	      int num[] = {100, 20, 30, 40, 50, 60, 70};
	      System.out.println(num[7]);
	   }
	}


Output:

Exception in thread "main" java. Lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 7
	at Test.main(Test.java:7)

Differences between Checked and Unchecked Exceptions in Java

The table below shows some of the notable differences between checked and unchecked exceptions in Java.

Key FactorsChecked ExceptionsUnchecked Exceptions
OccurrenceChecked exceptions occur at compile time.Unchecked exceptions occur at runtime.
Role of CompilerThe compiler checks a checked exception at compile time.The compiler does not check these exceptions.
HandlingHandled at compile time.Handled at run time.
Parent ClassException class is the direct parent class of the checked exception subclass.RuntimeException is the direct parent class of the Unchecked exception subclass.
Reason for OccurrenceA checked Exception occurs when the chances of failure are too high.RuntimeException is the direct parent class of the Unchecked exception subclass.
ExampleSQLException, IOException, ClassNotFoundException, InvocationTargetExceptionNullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, IllegalArgumentException,NumberFormatException

You might think of exceptions and errors as words that are analogous to each other. But they are not!

Best Practices for Checked and Unchecked Exceptions in Java

  • Use Checked Exceptions for Recoverable Errors: Use checked exceptions (like IOException or SQLException) for situations where the caller can recover from the exception (e.g., file not found, network error).
  • Use Unchecked Exceptions for Programming Errors: Use unchecked exceptions (like NullPointerException, ArrayIndexOutOfBoundsException) for errors that arise due to programming bugs or invalid arguments.
  • Provide Meaningful Messages: Always include descriptive error messages and relevant details when throwing exceptions, to help debug issues effectively.
  • Don’t Overuse Checked Exceptions: Avoid using checked exceptions excessively, as they can clutter method signatures and complicate code. Instead, prefer unchecked exceptions for non-recoverable errors.
  • Handle Exceptions Appropriately: Always catch exceptions only when you can handle them properly, and avoid empty catch blocks.
  • Document Exceptions: Clearly document the exceptions a method can throw to provide better understanding and error management for the users of your code.

Frequently Asked Questions

What is the difference between RuntimeException and exception in Java?

RuntimeException is a subclass of Exception in Java, representing unchecked exceptions that don't need to be declared or caught, unlike checked exceptions which require explicit handling.

What is the type of unchecked exception?

Unchecked exceptions in Java include subclasses of RuntimeException and Error. These exceptions don't need to be declared or caught explicitly, indicating critical errors or programming mistakes.

How do unchecked exceptions affect program flow?

Unchecked exceptions, such as RuntimeException, interrupt the normal flow of a program and are not required to be caught or declared. If not handled, they cause the program to terminate, potentially leading to program crashes.

Is ArithmeticException a checked or unchecked exception?

ArithmeticException is an unchecked exception in Java. It extends RuntimeException, meaning it doesn't need to be explicitly declared or caught, and is typically caused by arithmetic errors like division by zero.

Is NullPointerException checked or unchecked?

NullPointerException is an unchecked exception in Java. It extends RuntimeException and occurs when a program attempts to access or modify an object reference that is null, without needing explicit handling or declaration.

Conclusion

In conclusion, checked exceptions occur at compile time when the chances of failure are too high. In contrast, unchecked exceptions arise at runtime primarily due to syntax mistakes.

Eventually, after knowing the causes, types, and key differences between checked exception vs unchecked exception, you should start looking for ways to handle these exceptions in Java.

Live masterclass