Skip to main content

Command Palette

Search for a command to run...

Best Practices for Exception Handling in Java

Updated
โ€ข4 min read
Best Practices for Exception Handling in Java
N

I am a Tech Enthusiast having 13+ years of experience in ๐ˆ๐“ as a ๐‚๐จ๐ง๐ฌ๐ฎ๐ฅ๐ญ๐š๐ง๐ญ, ๐‚๐จ๐ซ๐ฉ๐จ๐ซ๐š๐ญ๐ž ๐“๐ซ๐š๐ข๐ง๐ž๐ซ, ๐Œ๐ž๐ง๐ญ๐จ๐ซ, with 12+ years in training and mentoring in ๐’๐จ๐Ÿ๐ญ๐ฐ๐š๐ซ๐ž ๐„๐ง๐ ๐ข๐ง๐ž๐ž๐ซ๐ข๐ง๐ , ๐ƒ๐š๐ญ๐š ๐„๐ง๐ ๐ข๐ง๐ž๐ž๐ซ๐ข๐ง๐ , ๐“๐ž๐ฌ๐ญ ๐€๐ฎ๐ญ๐จ๐ฆ๐š๐ญ๐ข๐จ๐ง ๐š๐ง๐ ๐ƒ๐š๐ญ๐š ๐’๐œ๐ข๐ž๐ง๐œ๐ž. I have ๐’•๐’“๐’‚๐’Š๐’๐’†๐’… ๐’Ž๐’๐’“๐’† ๐’•๐’‰๐’‚๐’ 10,000+ ๐‘ฐ๐‘ป ๐‘ท๐’“๐’๐’‡๐’†๐’”๐’”๐’Š๐’๐’๐’‚๐’๐’” and ๐’„๐’๐’๐’…๐’–๐’„๐’•๐’†๐’… ๐’Ž๐’๐’“๐’† ๐’•๐’‰๐’‚๐’ 500+ ๐’•๐’“๐’‚๐’Š๐’๐’Š๐’๐’ˆ ๐’”๐’†๐’”๐’”๐’Š๐’๐’๐’” in the areas of ๐’๐จ๐Ÿ๐ญ๐ฐ๐š๐ซ๐ž ๐ƒ๐ž๐ฏ๐ž๐ฅ๐จ๐ฉ๐ฆ๐ž๐ง๐ญ, ๐ƒ๐š๐ญ๐š ๐„๐ง๐ ๐ข๐ง๐ž๐ž๐ซ๐ข๐ง๐ , ๐‚๐ฅ๐จ๐ฎ๐, ๐ƒ๐š๐ญ๐š ๐€๐ง๐š๐ฅ๐ฒ๐ฌ๐ข๐ฌ, ๐ƒ๐š๐ญ๐š ๐•๐ข๐ฌ๐ฎ๐š๐ฅ๐ข๐ณ๐š๐ญ๐ข๐จ๐ง๐ฌ, ๐€๐ซ๐ญ๐ข๐Ÿ๐ข๐œ๐ข๐š๐ฅ ๐ˆ๐ง๐ญ๐ž๐ฅ๐ฅ๐ข๐ ๐ž๐ง๐œ๐ž ๐š๐ง๐ ๐Œ๐š๐œ๐ก๐ข๐ง๐ž ๐‹๐ž๐š๐ซ๐ง๐ข๐ง๐ . I am interested in ๐ฐ๐ซ๐ข๐ญ๐ข๐ง๐  ๐›๐ฅ๐จ๐ ๐ฌ, ๐ฌ๐ก๐š๐ซ๐ข๐ง๐  ๐ญ๐ž๐œ๐ก๐ง๐ข๐œ๐š๐ฅ ๐ค๐ง๐จ๐ฐ๐ฅ๐ž๐๐ ๐ž, ๐ฌ๐จ๐ฅ๐ฏ๐ข๐ง๐  ๐ญ๐ž๐œ๐ก๐ง๐ข๐œ๐š๐ฅ ๐ข๐ฌ๐ฌ๐ฎ๐ž๐ฌ, ๐ซ๐ž๐š๐๐ข๐ง๐  ๐š๐ง๐ ๐ฅ๐ž๐š๐ซ๐ง๐ข๐ง๐  new subjects.

Introduction

Exception handling is a crucial aspect of Java programming that allows developers to gracefully manage unexpected errors and ensure the robustness of their applications. When done correctly, exception handling can enhance the reliability and maintainability of Java code. In this article, weโ€™ll explore some best practices for dealing with exceptions in Java with examples.

Use Specific Exceptions

Instead of catching generic exceptions like Exception or Throwable, catch specific exceptions that accurately represent the error being handled. This enables better error diagnosis and allows for more targeted handling.

Bad Practice:

try {
    int result = 10 / 0;
} catch (Exception e) {
    System.out.println("An error occurred");
}

Good Practice:

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}

Handle Exceptions Appropriately

Decide whether to catch, throw, or propagate exceptions based on the situation. Catch exceptions only when you can handle them effectively; otherwise, let them propagate up the call stack to higher-level handlers.

Example:

public void processFile(String filePath) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(filePath));
    System.out.println(br.readLine());
    br.close();
}

Avoid Swallowing Exceptions

Never ignore exceptions by catching them and doing nothing. Always log exceptions with sufficient context to aid in troubleshooting.

Bad Practice:

try {
    int[] numbers = new int[5];
    System.out.println(numbers[10]); // Out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
    // Do nothing (swallowed exception)
}

Good Practice:

try {
    int[] numbers = new int[5];
    System.out.println(numbers[10]);
} catch (ArrayIndexOutOfBoundsException e) {
    System.err.println("Index out of bounds: " + e.getMessage());
}

Use Finally Blocks for Cleanup

When dealing with resources like files, database connections, or network sockets, use finally blocks to ensure proper cleanup.

Example:

BufferedReader br = null;
try {
    br = new BufferedReader(new FileReader("test.txt"));
    System.out.println(br.readLine());
} catch (IOException e) {
    System.err.println("Error reading file: " + e.getMessage());
} finally {
    if (br != null) {
        try {
            br.close();
        } catch (IOException e) {
            System.err.println("Error closing file: " + e.getMessage());
        }
    }
}

Follow Try-with-Resources (Java 7+)

For handling resources that implement the AutoCloseable interface, use try-with-resources.

Example:

try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
    System.out.println(br.readLine());
} catch (IOException e) {
    System.err.println("Error: " + e.getMessage());
}

The resource is automatically closed at the end of the block.

Avoid Catching Throwable

Catching Throwable or its subclasses like Error is discouraged unless absolutely necessary.

Bad Practice:

try {
    int x = 10 / 0;
} catch (Throwable t) {
    System.out.println("Something went wrong");
}

Good Practice:

try {
    int x = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}

Use Custom Exceptions Judiciously

Create custom exception classes when existing exceptions do not adequately represent the error condition.

Example:

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

public class CustomExceptionExample {
    static void checkAge(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be 18 or above");
        }
    }

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

Fail Fast

Throw an appropriate exception immediately when an error condition is detected.

Example:

public void setAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
    this.age = age;
}

Document Exception Handling

Document exceptions that methods may throw using @throws in JavaDoc.

Example:

/**
 * Reads a file and returns the first line.
 * @param filePath Path of the file.
 * @return First line of the file.
 * @throws IOException If file is not found or cannot be read.
 */
public String readFile(String filePath) throws IOException {
    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
        return br.readLine();
    }
}

Test Exception Scenarios

Write unit tests to cover different exception scenarios.

Example using JUnit:

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class ExceptionTest {
    @Test
    void testDivisionByZero() {
        Exception exception = assertThrows(ArithmeticException.class, () -> {
            int result = 10 / 0;
        });
        assertEquals("/ by zero", exception.getMessage());
    }
}

Conclusion

By following these best practices, Java developers can effectively manage exceptions, leading to more robust and reliable software systems. Exception handling should be an integral part of the development process, with careful consideration given to handling errors gracefully and maintaining application stability.

Would you like additional examples or refinements? ๐Ÿ˜Š

More from this blog

Naveen P.N's Tech Blog

94 posts