Java Programming Handbook

    How to Handle Exception in Java

    Introduction#

    In our previous blog, we discussed what exceptions are and why they occur. Now, let’s explore how to handle these exceptions in Java so that our programs don’t crash unexpectedly.

    Java provides several mechanisms to handle exceptions efficiently. In this blog, we will cover:

    • Why exception handling is necessary
    • Using try-catch blocks
    • The finally block
    • The throw and throws keywords
    • Best practices for exception handling

    Why Handle Exceptions?#

    Exception handling ensures that a program runs smoothly even when an error occurs. Without exception handling, the program will terminate abruptly when an exception arises. Handling exceptions properly allows us to:

    • Prevent application crashes
    • Display meaningful error messages to users
    • Ensure proper resource management (closing files, database connections, etc.)
    • Debug errors effectively

    Using Try-Catch Blocks#

    The most common way to handle exceptions in Java is by using try and catch blocks. The try block contains the code that may cause an exception, and the catch block handles the exception if it occurs.

    Syntax:#

    try { // Code that may cause an exception } catch (ExceptionType e) { // Handling the exception }

    Example:#

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

    Output:

    Error: Cannot divide by zero.

    In this example, instead of crashing, the program gracefully handles the division by zero error and displays a message.

    Using Multiple Catch Blocks#

    Sometimes, different types of exceptions can occur. We can use multiple catch blocks to handle them separately.

    Example:#

    public class MultipleCatchExample { public static void main(String[] args) { try { int[] numbers = {1, 2, 3}; System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException } catch (ArithmeticException e) { System.out.println("Arithmetic Exception occurred."); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array Index Out of Bounds Exception occurred."); } } }

    Output:

    Array Index Out of Bounds Exception occurred.

    The Finally Block#

    The finally block contains code that always executes, whether an exception occurs or not. It is commonly used for cleanup operations, such as closing files or releasing resources.

    Example:#

    public class FinallyExample { public static void main(String[] args) { try { int num = 10 / 0; } catch (ArithmeticException e) { System.out.println("Exception caught."); } finally { System.out.println("This will always execute."); } } }

    Output:

    Exception caught. This will always execute.

    Using throw to Manually Throw Exceptions#

    Java allows us to manually throw exceptions using the throw keyword. This is useful when we want to create custom error messages.

    Example:#

    public class ThrowExample { public static void main(String[] args) { int age = 15; if (age < 18) { throw new ArithmeticException("Age must be 18 or above."); } System.out.println("Access granted."); } }

    Output:

    Exception in thread "main" java.lang.ArithmeticException: Age must be 18 or above.

    Using throws in Method Declarations#

    The throws keyword is used in method declarations to indicate that a method might throw an exception. It does not handle the exception but informs the caller of the method that an exception may occur.

    Example:#

    public class ThrowsExample { static void checkAge(int age) throws ArithmeticException { if (age < 18) { throw new ArithmeticException("Age must be 18 or above."); } } public static void main(String[] args) { checkAge(15); } }

    Output:

    Exception in thread "main" java.lang.ArithmeticException: Age must be 18 or above.

    Best Practices for Exception Handling#

    To ensure good coding practices, follow these guidelines:

    • Catch only specific exceptions instead of using a generic Exception catch block.
    • Provide meaningful error messages for debugging and user guidance.
    • Use finally blocks for essential cleanup tasks.
    • Avoid empty catch blocks – Always take some action when catching exceptions.
    • Use throw and throws wisely to indicate expected errors in methods.

    Conclusion#

    In this blog, we learned:

    • How to handle exceptions in Java using try-catch blocks.
    • How to use multiple catch blocks for different exceptions.
    • The purpose of the finally block for resource cleanup.
    • How to manually throw exceptions using throw.
    • How to declare exceptions using throws.

    In the next blog, we will discuss Try and Catch Blocks in Detail, with more real-world examples and best practices.

    Last updated on Apr 09, 2025