Checked and Unchecked Exceptions in Java

Checked and Unchecked Exceptions in Java

In Java, the exceptions are broadly divided into checked and unchecked exceptions. Checked exceptions are checked at compile time, like IOException, while unchecked exceptions are runtime exceptions like NullPointerException. In this blog, we will discuss what exceptions are in Java, the exception lifecycle, the checked and unchecked exceptions, checked vs unchecked exceptions in Java, and how to handle these exceptions with best practices.

Table of Contents:

What are Exceptions in Java and Why Do They Occur

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

Common Types of Errors Represented by Java 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 is supposed to, e.g., the printer is not found.
  • Programming Bugs: There are logical errors or improper use of the API, e.g., accessing an array out of its bounds.

What is Java Exception Lifecycle

The exception lifecycle in Java involves throwing an exception, catching an exception, and handling an exception. Here is a brief description of the exception lifecycle 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 Java 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 class 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 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.

Java Error Handling Best Practices For Unchecked Exceptions

  1. Preventive Programming: Unchecked Exceptions focuses on writing code that avoids the common result of 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 debug errors quickly.
  5. Use Assertions for Debugging: Use the assert keyword to catch errors during programming.
  6. Detect and handle the errors as soon as possible instead of leaving them.

Checked Exceptions in Java

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

There are 2 types of Checked Exceptions. These are:

  • Fully Checked Exception: These are the checked exceptions where all their 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 subclasses 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.

Java Error Handling Best Practices For 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 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

How to Handle Checked and Unchecked Exceptions in Java

Here are a few ways for Java exception handling:

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: In the above Java try-catch example, the 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:  In the above Java try-catch example, 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, 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 Java try-catch example, 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: In the above Java try-catch example, the 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 programming errors.

when_to_

When to Use Checked Exceptions and Unchecked Exceptions in Java

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. 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

Difference Between Checked and Unchecked Exceptions in Java

Here is the comparison table for compile-time vs runtime 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!

Real-World Use Cases for Checked and Unchecked Exceptions in Java

Checked Exceptions:

  • Reading files: Like when you try to open a file that might not exist (IOException).
  • Connecting to a database: Things can go wrong, like the database not responding (SQLException).
  • Accessing the internet: A website might be down, or the URL is wrong (MalformedURLException).

Unchecked Exceptions:

  • Null values: Trying to use something that hasn’t been set (NullPointerException).
  • Wrong input: Passing the wrong type or value into a method (IllegalArgumentException).
  • Bad index: Trying to access an array element that doesn’t exist (ArrayIndexOutOfBoundsException).

Common Mistakes with Checked and Unchecked Exceptions in Java

Checked Exceptions Mistakes

  • Not handling or declaring them: Forgetting to use try-catch or throws for exceptions like IOException.
  • Catching exceptions too broadly: Using catch (Exception e) instead of specific types can hide real problems.
  • Empty catch blocks: Catching an exception but not doing anything about it means no message or fix for it.
    Swallowing important details: Not logging or rethrowing the exception, so it’s hard to know what went wrong.

Unchecked Exceptions Mistakes

  • Not validating input: Skipping checks can cause a NullPointerException or IllegalArgumentException.
  • Assuming data is always correct: Trusting that arrays, lists, or user input will never cause errors.
  • Overusing unchecked exceptions: Throwing unchecked exceptions for recoverable issues instead of using checked ones.
  • Bad exception design: Creating custom unchecked exceptions for things that should be checked (like file errors).

IOException vs NullPointerException

Here is the comparison table for IOException vs NullPointerException on the basis of different aspects:

Feature IOException NullPointerException
Type Checked Exception (Compile-time) Unchecked Exception (Runtime)
When it occurs During input/output operations (e.g., files) When accessing methods/fields on a null object
Needs handling? Yes, must use try-catch or throws No, it is optional, but should be prevented by checks
Common Cause File not found, read/write failure Using a variable that hasn’t been initialized
Checked by compiler Yes No
Package java.io java.lang
Example new FileReader(“missing.txt”) String s = null; s.length();

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 and 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 Java exception handling?

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

Q6. How do compile-time vs runtime exceptions in Java differ in terms of handling and program behavior?

Compile-time exceptions must be handled for the code to compile, while runtime exceptions occur during execution and may crash the program if not handled.

Q7. How do RuntimeException vs Exception in Java differ in terms of error handling and compiler checks?

RuntimeException is unchecked and doesn’t require explicit handling, while Exception (excluding RuntimeException) is checked and must be handled or declared.

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