Exception Handling in Java


Exception Handling in Java illustration

What is Exception?

Exceptions are unexpected events that disrupt the normal flow of program execution. While some can be handled programmatically, critical errors such as system-level failures can impact application stability. In Java, an exception is an object derived from the Throwable superclass.

When an exception occurs, a stack trace provides detailed diagnostic information, including:

  • Exception type such as java.lang.ArithmeticException)
  • Method call stack at the time of the exception
  • Class and method names
  • File names and line numbers (helpful for debugging)

Common causes of exceptions in Java include:

  • Invalid user input
  • Missing files
  • Network failures or other runtime anomalies

The Throwable Class Hierarchy

At the root of Java's exception hierarchy is the Throwable class, which has two main branches: Error and Exception. Examples of errors include InternalError, OutOfMemoryError, and AssertionError. Examples of exceptions include IOException and RuntimeException.

See: Throwable API Documentation

Types of Exceptions

Exceptions in Java fall into two categories: built-in and user-defined.

  1. Built-in exceptions are provided by Java libraries and can be classified as checked or unchecked exceptions.
    • Checked exceptions must be either caught or declared in the method signature. They are typically conditions that a program should recover from,such as IOException, SQLException.
    • Unchecked exceptions occur at runtime and are usually due to programming errors,such as NullPointerException, ArithmeticException).
  2. User-defined exceptions (custom exceptions) are created by programmers to handle application-specific scenarios and are helpful for debugging and edge-case handling.

Example:


public class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

public class TestCustomException {
    static void validate(int age) throws CustomException {
        if (age < 20) {
            throw new CustomException("Age is not valid for our purpose");
        } else {
            System.out.println("It is good");
        }
    }

    public static void main(String[] args) {
        try {
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter age:");
            int age = sc.nextInt();
            validate(age);
        } catch (CustomException ex) {
            System.err.println("Exception occurred: " + ex);
        }
    }
}
        

Exception Handling

In real-world applications, errors are inevitable due to invalid inputs, hardware failures, or unpredictable runtime conditions. Without proper handling, these can lead to application crashes and data loss.

Java provides a robust mechanism for handling such errors using try-catch blocks, the throw and throws keywords, and custom exception classes. This approach ensures smoother execution and better user experience by gracefully managing runtime anomalies.

Use try-catch blocks to catch and resolve exceptions.

The throw keyword is used to explicitly throw an exception. It can be used with both built-in and user-defined exceptions.

Syntax: throw new ExceptionType("Error message");

The throws keyword is used in method declarations to indicate that a method may throw certain exceptions. The caller must handle these using a try-catch block.

Syntax: type method_name(parameters) throws exception_list

Example:


static void validate(int age) throws CustomException {
    if(age < 18) {
        throw new CustomException("The age is invalid");
    }
}
        
		

The finally Block

The finally block ensures that important cleanup code executes regardless of whether an exception occurs. It's commonly used for releasing resources such as files or network connections.

Example:

		
public class SimpleFinallyBlock {
    public static void main(String[] args) {
        try {
            Scanner sc = new Scanner(System.in);
            int first = sc.nextInt();
            int second = sc.nextInt();
            int result = divide(first, second);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.err.println("Exception: " + e);
        } finally {
            System.out.println("Good Bye!!");
        }
      }
    public static int divide(int a, int b) {
        return a / b;
      }
    }
        
Yilma Goshime

I’m committed to providing tailored solutions and always ready to assist if any issue arises.

LetUsLearn