Java Programming Handbook

    Class Exception in Java

    Introduction#

    In Java, exceptions are objects that represent an error or an unexpected behavior in a program. These exceptions belong to the class hierarchy that extends java.lang.Throwable. In this blog, we will explore:

    • The Exception class hierarchy
    • Commonly used methods in the Exception class
    • Creating custom exceptions in Java

    By the end of this blog, you’ll have a strong understanding of how Java organizes exceptions and how you can extend the Exception class to create your own exceptions.

    Exception Class Hierarchy in Java#

    Java organizes exceptions into a well-structured hierarchy under the Throwable class:

    Throwable ├── Exception │ ├── IOException │ ├── SQLException │ ├── ClassNotFoundException │ ├── RuntimeException │ ├── ArithmeticException │ ├── NullPointerException │ ├── ArrayIndexOutOfBoundsException ├── Error ├── StackOverflowError ├── OutOfMemoryError
    • Throwable: The root class of all exceptions and errors.
    • Exception: Represents errors that can be recovered from.
    • RuntimeException: Represents unchecked exceptions.
    • Error: Represents serious issues that usually cannot be handled.

    Commonly Used Methods in the Exception Class#

    The Exception class provides several useful methods to get information about an exception:

    MethodDescription
    getMessage()Returns a detailed message of the exception.
    toString()Returns a string representation of the exception.
    printStackTrace()Prints the complete stack trace of the exception.

    Example:#

    public class ExceptionMethodsExample { public static void main(String[] args) { try { int result = 10 / 0; // This will throw ArithmeticException } catch (ArithmeticException e) { System.out.println("Message: " + e.getMessage()); System.out.println("toString(): " + e.toString()); System.out.print("StackTrace: "); e.printStackTrace(); } } }

    Output:#

    Message: / by zero toString(): java.lang.ArithmeticException: / by zero StackTrace: java.lang.ArithmeticException: / by zero at ExceptionMethodsExample.main(ExceptionMethodsExample.java:5)

    Creating Custom Exceptions in Java#

    Java allows developers to create their own exception classes by extending Exception.

    When Should You Create Custom Exceptions?#

    • When built-in exceptions do not represent a specific error scenario in your application.
    • When you want to define meaningful exception names for clarity.
    • When you need additional fields/methods in your exception class.

    Example: Custom Exception#

    class InvalidAgeException extends Exception { public InvalidAgeException(String message) { super(message); } } public class CustomExceptionExample { public static void validateAge(int age) throws InvalidAgeException { if (age < 18) { throw new InvalidAgeException("Age must be 18 or above to vote."); } System.out.println("Valid age for voting."); } public static void main(String[] args) { try { validateAge(16); } catch (InvalidAgeException e) { System.out.println("Caught Exception: " + e.getMessage()); } } }

    Output:#

    Caught Exception: Age must be 18 or above to vote.

    Best Practices for Using Exception Classes#

    • Use meaningful exception namesInvalidAgeException is clearer than Exception.
    • Extend Exception for checked exceptions and RuntimeException for unchecked exceptions.
    • Always provide descriptive error messages in custom exceptions.
    • Use built-in exceptions whenever possible instead of creating new ones unnecessarily.

    Conclusion#

    In this blog, we learned:

    • The hierarchy of exception classes in Java.
    • How to use common Exception class methods.
    • How to create and use custom exceptions.
    • Best practices for handling exceptions effectively.

    Next, we will explore Checked and Unchecked Exceptions in Java, where we’ll discuss their differences and when to use each.

    Last updated on Apr 09, 2025