top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Checked and Unchecked Exceptions in Java

Introduction

Exception handling in Java is an essential aspect of programming that allows developers to gracefully handle errors and unexpected situations that may arise during the execution of their code. Exceptions are categorized into two main types: checked and unchecked exceptions. Understanding the differences between these two is crucial for effective error handling in Java applications. This article will explore the concepts of Checked vs Unchecked Exceptions in Java. Readers can gain insight into the scenarios where each type is used. Checked and unchecked exception examples will also be provided.

Types of Exceptions

In Java, exceptions are objects that represent abnormal conditions or errors that occur during the execution of a program. These are classified into two main categories: checked exceptions and unchecked exceptions.

1. Checked Exception in Java

Checked exceptions, as the name suggests, are exceptions that the compiler checks at compile-time and verifies whether the code handles them appropriately. If a method can potentially throw a checked exception, it must either catch it or declare it in its method signature using the throws keyword.

Checked exceptions are typically used to handle exceptional conditions from which a well-written code should anticipate and recover. These often indicate situations that are beyond the programmer's control, such as I/O errors, network failures, or database connectivity issues. By forcing the programmer to handle or declare these exceptions, Java promotes robust error-handling practices.

Checked Exception Examples

The FileInputStream function from the java.io package is highlighted in red in the code below. The marking is because the compiler is making us handle a checked exception that this method throws. There are two ways to go about doing this.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class CheckedException {
    public void readFile() {
        String fileName = "file_does_not_exist.txt"; // Provide a valid file name
        File file = new File(fileName); // Corrected the file name
        try {
            FileInputStream stream = new FileInputStream(file);
            // You can add code here to read from the FileInputStream
        } catch (FileNotFoundException e) {
            System.err.println("Exception occurred: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        CheckedException example = new CheckedException();
        example.readFile();
    }
}

This code reads a file that does not exist, and if an exception occurs during the creation of the FileInputStream, the exception message is printed using System.out.println().

a). Using TRY CATCH.

Simply place a try catch block around the Java code that causes the checked exception to be thrown. You may now process and handle the exception as a result of this. This method makes it very simple to ignore the exception and continue as normal. You might encounter our good friend, the NullPointerException, later in the code, when the method performs something necessary.

By adding our code to the catch block, we can capture the exception and process the problem in a useful way, averting the emergency.

b). Throws

The checked exception is thrown up the stack to the called function using the keyword throws. FileInputStream just subjected you to this. We don't have to handle this exception because someone else will. The caller method must then take action with it, perhaps throwing it once again.

Consider who should be handling the issue and what piece of code is best suited to handle it appropriately before you toss every time, much like when you try to catch.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class CheckedException {
    public void readFile() throws FileNotFoundException {
        String fileName = "file_does_not_exist.txt"; // Provide a valid file name
        File file = new File(fileName); // Corrected the file name
        try {
            FileInputStream stream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            System.err.println("Exception occurred: " + e.getMessage());
            throw e;
        }
    }

    public static void main(String[] args) {
        CheckedException example = new CheckedException();
        try {
            example.readFile();
        } catch (FileNotFoundException e) {
            System.err.println("File not found.");
        }
    }
}

In this code, when the FileNotFoundException occurs during the creation of the FileInputStream, the exception statement is printed using System.err.println().

2. Unchecked Exception in Java

Unchecked exceptions, also known as runtime exceptions, are those that do not require to be checked by the compiler at compile time. Unlike checked exceptions, these do not need to be caught or declared in the method signature. They can occur at runtime and are generally caused by programming errors or invalid conditions that should have been prevented.

Unchecked exceptions are often used to indicate programming mistakes, such as dividing a number by zero (ArithmeticException) or accessing an array index out of bounds (ArrayIndexOutOfBoundsException). These anomalies usually represent critical errors that may require program termination or major corrective actions.

Examples of Unchecked Exceptions

a). BindException

This error is becoming more common since systems today are constructed from a large number of little microservices, where each does its own thing while communicating with one another, typically through HTTP. Finding a free port is all you can do about it. A single port can only be used by one system at once, and it is first come, first served. The simplest way is to use a different port since most online apps use port 8080 by default.

b). IndexOutOfBoundsException

When working with arrays, this is a relatively typical Java unchecked exception. If you attempt to access an index in an array that does not exist, it will alert you. You will receive this exception if you request item 11 when the array contains only a total of 10.

import java.util.ArrayList;
import java.util.List;

public class IndexOutOfBounds {
    public static void main(String[] args) {
        List<String> list1 = new ArrayList<>(); 
        list1.add("item-1");
        list1.add("item-2");
        list1.add("item-3");
       var result = list1.get(list1.size() - 1);
        System.out.println(result);
    }
}

The Java code mentioned above is a typical example of how to encounter an 

IndexOutOfBoundsException. The size of the array is 3, which makes sense because there are 3 items, but arrays are 0-based, thus, the last item in the array is at index 2. This is what confuses folks. It is always the size -1 to reach the final item.

When to Use Checked Exceptions and Unchecked Exceptions in Java

The decision to use checked or unchecked exceptions depends on the specific situation and the desired error-handling approach.

Checked exceptions are suitable when the code can reasonably anticipate and recover from unusual conditions. They force the developer to acknowledge and handle potential errors explicitly, promoting more robust and resilient code. Checked exceptions are commonly used in scenarios involving I/O operations, network communication, or accessing external resources like databases.

On the other hand, unchecked exceptions are often used for programming errors that are unlikely to be handled programmatically. They represent severe issues that require immediate attention and may necessitate program termination or significant corrective measures. Unchecked exceptions are typically used to catch unusual conditions like division by zero, null pointer dereference, or index out-of-bounds errors.

  Now, let's provide you with a list of checked and unchecked exceptions in Java.

 Checked Exceptions in Java

There are several standard checked exceptions in Java. These cover a wide range of scenarios and provide specific information about the exceptional conditions that may occur. Here is a list of checked exceptions in Java:

  • IOException: This exception is thrown when there is an error during input or output operations, such as reading from or writing to a file.

  • FileNotFoundException: It is thrown when an attempt is made to access a file that does not exist or cannot be found.

  • SQLException: This exception is related to database operations and is thrown when there is an error in interacting with a database, such as a connection failure or a query execution error.

  • ClassNotFoundException: It is thrown when an attempt is made to load a class dynamically using reflection, but the specified class cannot be found.

  • InterruptedException: This exception is thrown when a thread is interrupted while it is in a sleeping or waiting state.

  • ParseException: It is thrown when there is an error in parsing strings into a specific format, such as parsing a date string into a Date object.

  • MalformedURLException: This exception is thrown when there is an error in creating a URL object, typically due to an invalid URL format.

These are just a few examples of checked exceptions in Java. The Java API provides many more that cover various scenarios, including network operations, XML parsing, and more. When dealing with methods or APIs that declare checked exceptions, it is necessary to handle or declare these exceptions explicitly in your code.

Unchecked Exceptions in Java

In addition to checked exceptions, Java also has a set of unchecked exceptions known as runtime exceptions. Unlike the former, the latter do not require explicit handling or declaration. Here are some commonly encountered unchecked exceptions in Java:

  • NullPointerException: This exception occurs when an application attempts to access or manipulate a null object reference.

  • ArithmeticException: It is thrown when there is an error in arithmetic operations, such as division by zero.

  • ArrayIndexOutOfBoundsException: This exception occurs when an attempt is made to access an array element with an invalid index.

  • IllegalArgumentException: It is thrown when an invalid argument is passed to a method.

  • ClassCastException: This exception occurs when an attempt is made to cast an object to a class that it is not an instance of.

  • IllegalStateException: It is thrown when the state of an object is not as expected for a particular operation.

  • UnsupportedOperationException: This exception is thrown when an unsupported operation is attempted on a collection or iterator.

Checked Exceptions During Runtime

During runtime, checked exceptions in Java play a crucial role in ensuring the reliability and stability of applications. Although the compiler checks these at compile-time, their impact extends beyond the development phase.

When a method declares a checked exception in its signature, it serves as a contract with the calling code, indicating that the method can potentially encounter certain exceptional conditions. This contract requires the calling code to either handle the exception or propagate it further by declaring it in its own method signature using the throws keyword.

At runtime, if a method encounters a checked exception and does not handle it appropriately, the exception will propagate up the call stack until it reaches a try-catch block that can handle it. This ensures that exceptional conditions are not ignored and are ultimately addressed. 

For example, consider a method that reads data from a file and processes it. The method may declare a checked exception like IOException to indicate that it can encounter input/output errors during file operations. By handling or declaring this exception, developers can implement error recovery mechanisms, display appropriate error messages to users, or take alternative actions to ensure the smooth execution of the program.

However, it is important to note that excessive use of checked exceptions can lead to code clutter and increased complexity. Therefore, it is advisable to carefully consider whether a particular exceptional condition warrants a checked exception or if an unchecked exception would be more appropriate.

Conclusion

For effective error handling and the development of reliable programs, it is crucial to comprehend the notions of checked and unchecked exceptions in Java. Developers can handle predicted exceptional conditions explicitly by using checked exceptions. Unchecked exceptions, on the other hand, are signs of serious problems in programming that must be fixed right away. Programmers can improve the dependability and stability of their Java applications by implementing suitable exception-handling mechanisms and choosing the appropriate exception types.

FAQs

1. How are checked exceptions different from unchecked exceptions in Java?

Checked exceptions are checked by the compiler at compile-time and must be explicitly handled or declared in the method signature. Unchecked exceptions, on the other hand, are not checked by the compiler and do not require explicit handling or declaration.

2. How do you handle a checked exception in Java?

 A checked exception can be handled using a try-catch block. The code that may throw the checked exception is placed within the try block, and the catch block is used to specify the actions to be taken if the exception occurs.

3. How do you handle an unchecked exception in Java?

Unchecked exceptions do not require explicit handling. However, you can still handle them using try-catch blocks if you want to perform specific actions when the exception occurs. Otherwise, the unchecked exception will propagate up the call stack until it is caught or the program terminates.

4. What happens if you don't handle a checked exception in Java?

If a checked exception is not handled or declared in the method signature, it will result in a compilation error. The compiler ensures that all checked exceptions are appropriately handled or declared to promote proper error-handling practices.

5. What happens if you don't handle an unchecked exception in Java?

If an unchecked exception is not explicitly handled, it will propagate up the call stack until it is caught or the program terminates. These typically indicate critical errors or programming mistakes that may require immediate attention.

Leave a Reply

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