Skip to main content

Command Palette

Search for a command to run...

Exception Handling

Published
•2 min read•View as Markdown
Exception Handling
E

I am a passionate software engineer in training at ALX. I have a strong preference for back-end development. I am on course to share my learning journey with you.

Introduction

In the previous lesson, we explored Arrays and Collections, essential structures for storing and managing groups of data efficiently in Java. Now, we shift focus to Exception Handling, a crucial mechanism for ensuring robust and error-free programs.

Try-Catch Blocks

The try-catch block is used to handle exceptions and prevent runtime errors from crashing a program.

Example:

class TryCatchExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // This will cause an ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
        }
    }
}

/**
* Output:
* Cannot divide by zero!
*/

Finally Clause

The finally block is always executed, whether an exception is thrown or not. It is useful for resource cleanup.

Example:

class FinallyExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[5]); // This will cause an ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Index out of bounds!");
        } finally {
            System.out.println("Execution completed.");
        }
    }
}

/**
* Output:
* Index out of bounds!
* Execution completed.
*/

Custom Exceptions

You can define your own exception classes by extending Exception or RuntimeException.

Example:

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

class CustomExceptionExample {
    static void checkAge(int age) throws CustomException {
        if (age < 18) {
            throw new CustomException("Age must be 18 or older.");
        }
    }

    public static void main(String[] args) {
        try {
            checkAge(16);
        } catch (CustomException e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }
}

/**
* Output:
* Caught exception: Age must be 18 or older.
*/

Conclusion

Exception handling ensures that Java programs can gracefully handle errors and maintain stability. Using try-catch blocks, finally clauses, and custom exceptions allows for better error management, making programs more robust and user-friendly.

Stay tuned for the next topic in the Java Short Notes series!

More from this blog

Enchill Blogs

22 posts

I am a passionate software engineer in training at ALX. I have a strong preference for back-end development. I am on course to share my learning journey with you.