Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Checked and Unchecked Exceptions in Java

Last Updated on October 16, 2023 by Ankit Kochar

Today, we’ll delve into the realm of Checked and Unchecked Exceptions, complete with illustrative examples to enhance our comprehension of this subject. Initially, we’ll explore Java’s Exception Handling and the various categories it encompasses. Subsequently, we’ll delve into the situations and contexts that warrant the use of checked and unchecked exceptions. Finally, we’ll examine notable distinctions between checked and unchecked exceptions in the Java programming language.

Exceptions and Exception Handling in Java

Exceptions are events that occur during the execution of a Java program that disrupts the normal flow of the program’s instructions. These events are typically associated with error conditions, such as division by zero or trying to access an index that is out of the bounds of an array, that prevents the program from continuing normal execution.

There are two types of Built-in exceptions in Java: checked exceptions and unchecked exceptions as shown in the image given below:

Exception handling in Java is a mechanism that allows you to handle errors or exceptional conditions that may occur in a program. The process of handling exceptions involves capturing the exception, examining its information, and then taking appropriate action to resolve the error.

In Java, exceptions are thrown by the Java Virtual Machine (JVM) or by the code in a program when an error or exceptional condition occurs. To handle exceptions in Java Programming Language, you use the try-catch statement. The try block contains the code that might throw an exception, and the catch block contains the code that will be executed if an exception is thrown.

Syntax of try-catch block is:

try {
   // These statements/code might throw an exception 
} catch (ExceptionType e) {
   // code to handle the exception
}

It’s also possible to use the finally block to ensure that certain code is executed regardless of whether an exception is thrown or not. The finally block is optional and can be used to release resources or perform other clean-up actions.

Alongside the try-catch statement, Java offers the throws clause as a tool to declare that a method potentially throws a particular exception. This declaration enables the calling code to either manage the exception or transmit it up the call stack to the subsequent program level.

Now, since we are well equipped with the knowledge of exceptions and the process of Exception Handling in Java, Let’s deep dive into the topic of Checked Exceptions.

What are Checked Exceptions in Java?

In Java, checked exceptions are exceptions that the Java compiler checks for and requires you to handle or declare in your code. Checked exceptions are typically used to indicate a recoverable error, such as when a file cannot be found or a network connection cannot be established.

Checked exceptions are a subset of exceptions in Java that are derived from the Exception class. In contrast to unchecked exceptions, they have to be either caught and dealt with using a try-catch block or explicitly declared in the throws clause of the method where they might occur. This enforcement of handling or declaration is enforced by the Java compiler, which raises a compile-time error if a checked exception is left unhandled or undeclared.

IOException, SQLException, and InterruptedException are some examples of Built-in Checked Exceptions in Java.

Examples of Checked Exceptions

Commonly occurring Checked Exceptions are discussed below:
1. IO Exception
This exception is thrown when an input/output operation fails, such as reading from a file that doesn’t exist.

import java.io.*;

class Main {
  public static void main(String[] args) {
    try {
      File file = new File("test.txt");
      FileReader reader = new FileReader(file);
      reader.read();
    } catch (IOException e) {
      System.out.println("An IOException occurred: " + e.getMessage());
    }
  }
}

Output:

An IOException occurred: test.txt (No such file or directory)

Explanation:
In this example, we are trying to read a file named “test.txt”. Since the file does not exist, it throws an IOException while reading the file. This IOException caught the catch block and the error message is printed to the console.

2. SQL Exception
This exception is thrown when an error occurs while working with a database.

import java.sql.*;

class Main{
    public static void main (String[] args){
        // your code goes here
        try {
    		Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db");
    		Statement statement = connection.createStatement();
    		statement.executeQuery("SELECT * FROM users");
    	} catch (SQLException e) {
    		System.out.println("A SQLException occurred: " + e.getMessage());
    	}	
    }
}

Output:

A SQLException occurred: No suitable driver found for jdbc:sqlite:test.db

Explanation:
In this example, a connection to an SQLite database is established using the “DriverManager.getConnection” method. The SQL statement "SELECT * FROM users" is then executed using a Statement object. If an error occurs while accessing the database, an SQLException is thrown and caught in the catch block and then we have printed the error message on the console screen.

3. Interrupted Exception
The InterruptedException in Java is thrown when a thread is interrupted.

class Main {
  public static void main(String[] args) {
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      System.out.println("The thread was interrupted.");
    }
  }
}

Output:

The thread was interrupted.

Explanation:
In this example, the main method is sleeping for one second using the Thread.sleep() method. If the sleep method is interrupted by another thread, the InterruptedException is thrown and caught in the catch block. Then we print the message "The thread was interrupted" on the console screen.

What are Unchecked Exceptions in Java?

In Java, unchecked exceptions are exceptions that the Java compiler does not enforce checking for. These exceptions are usually associated with runtime errors that occur when a program violates an assumption about the system’s state, such as going beyond the bounds of an array or encountering a null pointer. In contrast to checked exceptions, there is no requirement to declare or explicitly handle unchecked exceptions in your code.

Examples of unchecked exceptions in Java include NullPointerException, ArithmeticException, and ArrayIndexOutOfBoundsException. Unchecked exceptions indicate a bug in the code and should be fixed, rather than simply being handled.

It’s good practice to catch unchecked exceptions and handle them appropriately, as they can still cause your program to crash if left unhandled. However, unlike checked exceptions, you are not required to do so by the Java compiler.

Examples of Unchecked Exceptions

Let us understand some of the commonly occurring Unchecked Exceptions in Java with the help of examples given below:

1. NullPointer Exception
This exception is thrown when an application tries to access an object through a null reference.

class Main {
  public static void main(String[] args) {
    try{
    	String str = null;
    	System.out.println(str.length());
    } catch (Exception e){
    	System.out.println("NullPointerException Occurred: " + e.getMessage());
    }
  }
}

Output:

NullPointerException Occurred: null

Explanation:
In this example, a string variable str is declared but not initialized. When the length of the string is attempted to be accessed using the length() method, a NullPointerException is thrown. The “catch” block will catch the exception, then we print the error message on output console.

2. Arithmetic Exception
This exception is thrown when an arithmetic operation such as dividing by zero is performed.

class Main {
  public static void main(String[] args) {
    try{
    	int x = 10;
    	int y = 0;
    	System.out.println(x / y);
    } catch (Exception e){
    	System.out.println("ArithmeticException Occurred: " + e.getMessage());
    }
  }
}

Output:

ArithmeticException Occurred: / by zero

Explanation:
In this example, an ArithmeticException is thrown when the value of x is divided by y, which has a value of zero. Division by zero is undefined in mathematics and results in an ArithmeticException in Java. The “catch” block will catch the ArithmeticException, then we print the “ArithmeticException Occurred” with the error message on output console.

3. Array Index Out Of Bounds Exception
This exception is thrown when an array is accessed with an index that is outside its bounds.

class Main {
  public static void main(String[] args) {
    int[] arr = new int[] {1, 2, 3, 4, 5};
    try {
      System.out.println(arr[5]);
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("ArrayIndexOutOfBoundsException occurred: " + e.getMessage());
    }
  }
}

Output:

ArrayIndexOutOfBoundsException occurred: Index 5 out of bounds for length 5

Explanation:
In this example, an array of integers named “arr” is created and initialized with 5 elements. When an attempt is made to access the 6th element of the array using arr[5], an “ArrayIndexOutOfBoundsException” is thrown. The ArrayIndexOutOfBoundsException is caught in the catch block and a message indicating that the exception has occurred is printed to the console

When to use Checked and Unchecked Exceptions in Java?

In Java, it is advisable to employ checked exceptions when an exception signifies a situation that can be feasibly addressed or recovered from in the program’s logic. On the other hand, unchecked exceptions should be utilized for situations that are unrecoverable, typically stemming from programming errors that require correction in the code.

Checked exceptions should be used in cases where the program can reasonably anticipate the exception and take appropriate action to handle it. For example, if a method that reads data from a file, it might throw a FileNotFoundException if the specified file is not found. The calling code can catch this exception and handle it in a meaningful way, such as displaying an error message to the user or prompting them to choose a different file.

Unchecked exceptions should be used in cases where the program cannot reasonably anticipate the exception or where the exception represents a programming error that should be fixed. For example, if a method tries to access an array with an index that is outside the bounds of the array, it will throw an ArrayIndexOutOfBoundsException, which is an unchecked exception. This exception indicates that the program is using the array incorrectly and should be fixed.

It’s important to note that checked exceptions require more boilerplate code to handle since they need to be either caught or declared in the method signature. This can make the code more verbose, but it also forces the developer to think about the potential exceptions that might be thrown and to handle them appropriately. On the other hand, unchecked exceptions are often easier to work with, since they don’t require explicit handling, but they can lead to unexpected behavior if they are not properly handled.

Difference Between Checked and Unchecked Exceptions in Java

Main differences between Checked and Unchecked Exceptions in Java are summarized in the following table:

Feature Checked Exceptions Unchecked Exceptions
Definition Exceptions that must be either caught or declared in the method signature. Exceptions that do not need to be handled.
Use case For conditions that can be reasonably recovered from. For conditions that cannot be recovered from, such as programming errors.
Propagation Must be either caught or declared in the method signature. Can be propagated up the call stack without being caught.
Coding overhead More coding overhead due to the requirement to handle or declare exceptions. Less coding overhead, since exceptions do not need to be handled.
Example FileNotFoundException, IOException, SQLException. NullPointerException, ArrayIndexOutOfBoundsException, IllegalArgumentException.
Syntax Must be surrounded by a try-catch block or declared in the method signature. Do not need to be surrounded by a try-catch block.
Execution time Slows down the execution of the program. Does not slow down the execution of the program.
Error reporting Provides more detailed error information. Provides less detailed error information.
Maintenance Easier to maintain since the programmer is forced to handle exceptions. More difficult to maintain since exceptions are not always handled.
Performance Slower performance due to the overhead of handling exceptions. Faster performance since exceptions does not need to be handled.
Debugging Easier to debug, since the exception is clearly defined. More difficult to debug, since the cause of the exception is not always clear.
Portability Portable, since the exception handling mechanism is clearly defined. Less portable, since the behavior of unchecked exceptions may vary between different implementations.
Documentation Better documented, since exceptions are clearly defined. Less well documented, since unchecked exceptions are often not well defined.
User experience Better user experience, since exceptions can be handled and the program can continue executing. Worse user experience, since exceptions may cause the program to terminate.
Testability Easier to test, since exceptions can be clearly defined and handled. More difficult to test, since exceptions may be propagated up the call stack and not always handled.
Predictability More predictable behavior, since exceptions are clearly defined and handled. Less predictable behavior, since exceptions may be propagated up the call stack and not always handled.

Conclusion
Understanding checked and unchecked exceptions in Java is fundamental to writing robust and reliable code. Checked exceptions are typically used for recoverable conditions, where you want to ensure that exceptions are either handled or declared. Unchecked exceptions, on the other hand, are used for unrecoverable conditions, often tied to programming errors.

Frequently Asked Questions (FAQs) Related To checked and unchecked exception

Here are some common questions and answers regarding checked and unchecked exceptions in Java:

1. Can you provide examples of checked exceptions?

Examples of checked exceptions include IOException, SQLException, and ClassNotFoundException. These exceptions represent scenarios where you should anticipate and handle potential issues, such as file not found or database connection problems.

2. What are some common examples of unchecked exceptions?

Common examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, and IllegalArgumentException. These exceptions typically result from programming errors or invalid input and are not required to be explicitly caught or declared.

3. When should I use checked exceptions vs. unchecked exceptions?

Checked exceptions should be used for situations where you expect a recoverable error condition, and you want to ensure that it is either handled or explicitly declared. Unchecked exceptions should be used for scenarios that are difficult or impossible to recover from, often related to programming errors.

4. What happens if I don’t handle or declare a checked exception?

If you don’t handle or declare a checked exception, the Java compiler will generate a compile-time error, indicating that you need to address the exception either by catching it or declaring it in the throws clause of the method.

5. Are there any best practices for exception handling in Java?

Best practices for exception handling in Java include handling exceptions at the appropriate level of abstraction, providing meaningful error messages, and documenting exception behavior in your code.

Leave a Reply

Your email address will not be published. Required fields are marked *