Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java Exception Handling Mechanisms

Tech May 17 2

Understanding Java Exceptions

Exceptions in Java represent unexpected events or errors that occur during program execution. These can disrupt the normal flow of the application if not properly managed.

Exception Hierarchy

All exceptions in Java are derived from the Throwable class, which has two main subclasses: Error and Exception. The Exception class itself has numerous subclasses, including RuntimeException.

Throwable Class Methods

The Throwable class provides several methods to obtain exception information:

  • getMessage() - Returns a detailed message about the exception
  • toString() - Provides a brief description of the exception
  • printStackTrace() - Outputs the exception's class, message, and stack trace to the console

Runtime vs. Checked Exceptions

In Java's exception hierarchy, all subclasses of Exception except RuntimeException are considered checked exceptions. These require explicit handling through either:

  1. Using try-catch blocks to handle the exception
  2. Declaring the exception with the throws keyword for the caller to handle

Common Runtime Exceptions

RuntimeExceptions include NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, and ClassCastException.

Exception Handling Syntax

Exception Handling with Try-Catch

The following example demonstrates exception handling in a division operation:

public class DivisionExample {
    public static int performDivision(int dividend, int divisor) {
        return dividend / divisor;
    }
    
    public static void main(String[] args) {
        int numerator = 10;
        int denominator = 0;
        
        try {
            int result = performDivision(numerator, denominator);
            System.out.println("Result: " + result);
        } catch (Exception e) {
            System.out.println("Error occurred: " + e.getMessage());
            return;
        } finally {
            System.out.println("Finally block executed");
        }
        
        System.out.println("Program continues after exception handling");
    }
}

Try-Catch Syntax Rules

  • The try block is mandatory
  • Multiple catch blocks are allowed, but parent exception catchers must follow child exception catchers
  • Catch blocks must immediately follow try blocks

The Finally Block

The finally block executes regardless of whether an exception occurred. Its syntax follows:

try {
    // Code that may throw exceptions
} catch (Exception e) {
    // Exception handling code
} finally {
    // Code that always executes
}

Throwing Exceptions

Java provides two keywords for throwing exceptions:

  • throws - Declares exceptions that a method might throw
  • throw - Explicitly throws an exception within a method

Example using throws:

public class AgeValidator {
    public static void validateAge(int age) throws Exception {
        if (age <= 0) {
            throw new Exception("Invalid age: must be a positive number");
        }
        System.out.println("Valid age: " + age);
    }
    
    public static void main(String[] args) {
        try {
            validateAge(-5);
        } catch (Exception e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }
}

Custom Exception Classes

To create custom exceptions, extend the Exception class or its subclasses:

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

public class Calculator {
    public static int divide(int dividend, int divisor) throws NegativeNumberException {
        if (divisor < 0) {
            throw new NegativeNumberException("Divisor cannot be negative");
        }
        return dividend / divisor;
    }
    
    public static void main(String[] args) {
        try {
            int result = divide(20, -4);
            System.out.println("Result: " + result);
        } catch (NegativeNumberException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.