Understanding Checked vs Unchecked Exceptions in Java

Understanding Checked vs Unchecked Exceptions in Java

In Java, the exceptions are broadly divided into checked and unchecked. Checked exceptions are checked at compile time, like IOException, while unchecked exceptions are runtime exceptions like NullPointerException

In this blog, we will be discussing more about the checked and unchecked exceptions in Java.

Table of Contents:

What is an Exception in Java?

An exception in Java is an error. It is defined as the event that occurs during the runtime and interrupts the flow of the program. When an exception occurs, the JDK creates an instance of the exception and stops the flow of the program unless and until the exception is handled properly.

There are two types of exceptions:

  • Unchecked exceptions
  • Checked exceptions

Types of Errors Represented by Exceptions

Exceptions represent a wide variety of errors, including, but not limited to:

  • User Input Errors: It is thrown when Incorrect input is given by the user
  • File Handling: It occurs during the reading, writing, or using of a file. 
  • Network Issues: It occurs when the user is doing network operations, e.g., the server is not responding.
  • Hardware Failures: This error occurs when the hardware of the device does not perform the way it has to be e.g., printer not found.
  • Programming Bugs: There are the logical errors or improper use of the API, e.g., accessing an array out of its bounds.

The Lifecycle of an Exception

Let us discuss some of the points that will make us understand how exceptions are thrown and caught in Java.

  1. Throwing an Exception: 

An exception is thrown by the program using a throw statement. The runtime system searches the call stack for a method that contains a block of code that can handle the thrown exception. This block of code is called an exception handler.

  1. Catching an Exception: 

To catch an exception, a method must provide a set of catch blocks that identify the type of exception it can handle. If the runtime system successfully finds a matching catch block, the exception is considered handled.

  1. Handling an Exception: 

The exception handling code inside the catch block is executed. After handling the exception, the program’s control flow continues after the try-catch block.

Unchecked Exceptions in Java

An exception that occurs at runtime is known as an unchecked exception. These exceptions are not checked at compile time and do not require direct handling. In Java, exceptions under the  RuntimeException classes are the unchecked exceptions, while everything else under the Throwable is a checked exception. These exceptions are caused by programming errors, such as accessing an out-of-bounds index in an array or attempting to divide by zero.  

These exceptions are usually the result of programming mistakes and can be avoided through proper code design. 

Because unchecked exceptions typically indicate issues that should be fixed during development, they can often be avoided through proper coding practices, such as input validation 

Examples of Unchecked Exceptions: 

  • NoSuchElementException
  • UndeclaredThrowableException
  • EmptyStackException
  • ArithmeticException
  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • SecurityException
Master Java Today - Accelerate Your Future
Enroll Now and Transform Your Future
quiz-icon

Characteristics of Unchecked Exceptions

1. Runtime Checking: They are not checked at compile time, meaning the compiler does not handle these exceptions forcefully.

2. Inherited from RuntimeException: Unchecked exceptions are the subclasses of the RuntimeException.

3. Indicates Programmer Errors: They often result in mistakes in the program logic, such as accessing null objects.

4. Optional Handling: The unchecked exceptions are not required to be handled. The programmer can handle them if necessary, but sometimes they are left, which leads to the crashing of the code.

Best Practices for Dealing with Unchecked Exceptions

1. Preventive Programming: Unchecked Exceptions focus on writing the code that avoids the common result of the unchecked exceptions. For example, check for null values before using an object or array.

2. Use Assertions: Use assertions to check the assumptions in the code. This can help catch unexpected conditions during development.

3. Minimize the Use of Try-Catch Blocks: Do not use too many try-catch blocks for unchecked exceptions.

4. Use Meaningful Exception Messages: When throwing the exceptions, give a clear message to help the user to debug for errors quickly.

5. Use Assertions for Debugging: Use the assert keyword to catch the errors during programming.

6. Detect and handle the errors as soon as possible instead of leaving them.

Checked Exceptions in Java

Checked Exceptions are the exceptions that are checked at the compile time. If a method throws a checked exception, then the exception must be fixed using the try-catch block.

There are 2 types of Checked Exceptions. These are:

  • Fully Checked Exception: These are the checked exceptions where all its child classes are also checked, e.g., IOException, InterruptedException.
  • Partially Checked Exception:  These are the checked exceptions where some of their child classes are unchecked, e.g., custom subclasses of Exception not extending RuntimeException

All the checked exceptions are subclass of an Exception. Unlike unchecked exceptions, checked exceptions must be caught by the user 

Common Examples of Checked Exceptions

  • NoSuchFieldException
  • InterruptedException
  • NoSuchMethodException
  • ClassNotFoundException

Characteristics of Checked Exceptions

1. Checked at Compile-Time: The compiler makes sure that the checked exceptions are used within a try-catch block or within the method’s signature by using the throws keyword. If they are not used properly, the code will not compile.

2. Subclass of Exception: Checked exceptions are the direct or indirect subclasses of java.lang.Exception, except the RuntimeException.
Examples: IOException, FileNotFoundException

3. Mandatory Handling: The programmer is forced to handle the checked exceptions explicitly, knowing the potential errors before runtime.

4. Used for Recoverable Conditions: Checked exceptions are used for the conditions from which the program can recover, like database connectivity issues.

Best Practices for Handling Checked Exceptions

1. Use Try-Catch Block: Put the code that can throw an exception within a try-catch block. This will handle the exception.

2. Use Throws Keyword: If the exception is to be controlled by the caller of the method, use the exception in the method’s throws clause.

3. Provide Useful Error Messages: use messages or actions to help to find the solution when catching an exception so that recovering from the error is easy.

4. Avoid overusing the throws: Do not declare too many exceptions in the throws clause of the method, as it can make your API hard to use.

Unlock Your Future in Java
Start Your Java Journey for Free Today
quiz-icon

Java Exception: Handling Checked and Unchecked Exceptions

1. Handling the checked exception in Java

There are mainly 2 methods to handle the checked exception. These are:

  • Using the try-Catch Blocks: This is the most common approach for handling checked exceptions. The idea is to put the code that can throw an exception inside a try block and then catch the exception.  

Example: FileNotFound Exception

Java

Output:

Handling the checked exception in java using try

Explanation: The above code tries to open a file called “nonexistentfile.txt”  which doesn’t exist, and hence it throws a FileNotFoundException, which is caught by the catch block.

  • Using the throws keyword: The throws keyword allows a method to see if the code can throw an exception and passes the responsibility of handling the exception to the caller.

Example:  FileNotFound Exception

Java

Output:

Handling the checked exception in java using throws

Explanation: The readFile() method shows that it can throw a FileNotFoundException by using the throws keyword. The main() method calls the readFile() method and catches the exception through a try-catch block. This allows the exception to be passed to the user.

NOTE: Checked exceptions are required to be handled or declared with the throws keyword, ensuring that they are addressed during development.

2. Handling the unchecked exception in Java 

There are mainly 2 methods to handle the unchecked exception. These are: 

  • Using try-catch Block: You can handle the unchecked exceptions using a try-catch block. While they are not important to handle, but catching them can be useful where you want to prevent the application from crashing.

Example: Arithmetic Exception

Java

Output:

Handling the unchecked exception in Java using try

Explanation: In the above code, a try-catch block is used to handle an exception. Inside the try block, a division by zero occurs, which throws an ArithmeticException. The catch block catches the exception and prints the error message.

  • Using the throws Keyword: You can also check unchecked exceptions using the throws keyword. However, since unchecked exceptions are not required to be declared, this is usually not necessary.

Example: ArithmeticException

Java

Output:

Handling the unchecked exception in Java using throws

Explanation: The above code shows how the throws keyword is used to declare an unchecked exception (ArithmeticException). In the main() method, the exception is handled using a try-catch block, where the exception is caught, and the error message “Error caught in main: / by zero” is printed when division by zero occurs.

NOTE: Unchecked exceptions are optional to handle or declare; they only indicate the programming errors.

when_to_

When to Use Checked Exceptions and Unchecked Exceptions

When to Use the Checked Exceptions:

1. Recoverable Errors: When the exception is recoverable, meaning the caller can take the actions to recover from it. For example, if a file is not found, the caller might  try to create the file or ask for a new file path

2. Predictable and Specific Conditions: When the exception is expected to occur as part of normal operation also. Example: IOException, InterruptedException.

3. External Resources: If your code communicates with external resources like files and databases, you should use the checked exceptions, e.g., IOException and SQLException.

When to Use the Unchecked Exceptions:

1. Programming Errors (Bugs): When the error is a programming error that can not be recovered, e.g., NullPointerException, ArrayIndexOutOfBoundsException. This happens because of logic errors or improper usage.

2. Unexpected Scenarios: Use unchecked exceptions when an invalid argument is passed to a method.Example: IllegalArgumentException

3. Avoiding repetitive Code: If the exception shows a situation where the caller doesn’t need to handle it, you should use the unchecked exceptions. Example: ArithmeticException

Differences Between Checked and Unchecked Exceptions in Java

Aspect Checked Exceptions Unchecked Exceptions
Definition Exceptions that are checked at compile time. Exceptions that occur at runtime
Example IOException, SQLException, ClassNotFoundException ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
Handling Requirement Must be either caught using a try-catch block or declared using the throws keyword. Not required to be explicitly handled or declared.
Declaration with throws Required if the exception is not handled inside the method. Not required as they are not checked by the compiler.
Compile-Time Checking Checked by the compiler to ensure that the exception is properly handled. handled at runtime.
Usage Typically used for recoverable conditions that are expected and can be handled. Typically used for programming errors, which are often preventable through proper coding.
Example of Handling try-catch block or throws keyword. try-catch block 
Cause External factors or conditions like I/O issues or missing classes. Programming errors, such as invalid calculations or accessing a null object.
Inheritance Inherited from Exception class Inherited from RuntimeException or Error.
Design  Forces developers to handle potential errors, increasing code reliability. Indicates programming errors that usually should be fixed rather than handled at runtime.

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

In Java, checked exceptions must be handled either with try-catch blocks or declared with throws. These exceptions are checked at compile-time and often arise due to external issues (like file handling). On the other hand, unchecked exceptions occur at runtime due to programming errors (like dividing by zero) and don’t require explicit handling, but should be prevented through good coding practices.

If you want to learn more about Java, you can refer to our Java Course.

Checked vs Unchecked Exceptions in Java – FAQs

Q1. What is an exception in Java?

An exception in Java is an unexpected condition that generally arises whenever you execute a particular program that breaks the flow of statements.

Q2. What is the difference between checked and unchecked exceptions in Java?

Checked exceptions are checked at compile time. Unchecked exceptions are checked at run time. External factors like file I/O and database connection cause the checked exception.

Q3. Is NullPointerException checked or unchecked?

NullPointerException is an unchecked exception, so we don’t have to catch it. It can be prevented using null checks and preventive coding techniques.

Q4. How to tell if an exception is checked or unchecked?

When an exception must be handled with try-and-catch semantics, it is known as a checked exception. If try-and-catch semantics are not required, it is known as an unchecked exception.

Q5. What are the 5 keywords of exception handling in Java?

In Java, the key exception-handling keywords are try, catch, finally, throw, and throws.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner