print
Advertisment
Advertisment

Exception hierarchy

Demystifying Exception Hierarchies in Java

Exception handling is a cornerstone of robust Java programming. It empowers developers to anticipate and gracefully handle errors that may arise during program execution. One of the essential aspects of Java's exception handling mechanism is the concept of "Exception Hierarchies." In this blog, we delve deeper into this topic, shedding light on how exceptions are organized and managed in Java.

Understanding Exception Hierarchies

At the core of Java's exception hierarchy is the "Throwable" class, which serves as the superclass for all exceptions. This hierarchical structure classifies exceptions into two main categories: checked exceptions, which are subclasses of "Exception," and unchecked exceptions, which are subclasses of "RuntimeException." The primary distinction between these categories is that checked exceptions must be either caught using try-catch blocks or declared in the method signature, whereas unchecked exceptions need not be explicitly handled.

Product.java

public class Product {
    private String name;

    public Product(String name) {
        this.name = name;
    }

    public void setName(String name) {
        if (name == null) {
            throw new IllegalArgumentException("Name cannot be null");
        }
        this.name = name;
    }

    public String getName() {
        return name;
    }
}
    
Advertisment

In the following example, we create a "Product" class with getter and setter methods for the product's name. In the setName method, we use an unchecked exception, "IllegalArgumentException," to indicate that the name cannot be set to null. This unchecked exception propagates up the call stack, demonstrating how exceptions flow through the hierarchy.

Main.java

public class Main {
    public static void main(String[] args) {
        Product product = new Product("Laptop");

        try {
            product.setName(null);
        } catch (IllegalArgumentException e) {
            System.out.println("IllegalArgumentException: " + e.getMessage());
        }
    }
}
    

In the "Main" class, we create an instance of the "Product" class and attempt to set its name to null, triggering the "IllegalArgumentException." We catch and handle this exception in a try-catch block, demonstrating how checked exceptions are managed.

Conclusion

Exception hierarchies in Java are a fundamental tool for building reliable and resilient applications. By understanding the classification of exceptions into checked and unchecked categories, developers can write code that gracefully handles errors, enhances code clarity, and ensures the stability of Java applications.

Advertisment
Advertisment
arrow_upward