Skip to main content

Lesson 6 of 8

Exception Best Practices

Exceptions are often misused - swallowed silently, caught too broadly, or used for flow control. These anti-patterns lead to bugs that are nearly impossible to debug. Learning what NOT to do is as important as the mechanics.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Common Anti-Patterns & Correct Patterns

Common Anti-Patterns & Correct Patterns
public class ExceptionBestPractices {

    // ❌ ANTI-PATTERN 1: Empty catch - silently swallows errors
    public void swallowed() {
        try {
            riskyOperation();
        } catch (Exception e) {
            // Nothing here - error completely hidden!
            // Production bugs nightmare
        }
    }
    // ✅ At minimum: log the exception
    public void logged() {
        try {
            riskyOperation();
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
            // Or: logger.error("riskyOperation failed", e);
        }
    }

    // ❌ ANTI-PATTERN 2: Catching Exception (too broad)
    try {
        connectToDatabase();      // throws SQLException
    } catch (Exception e) {       // catches NPE, IllegalArgument, everything!
        handleConnectionFailure();// "connection failure" might not be the cause
    }
    // ✅ Catch the specific type
    try {
        connectToDatabase();
    } catch (SQLException e) {
        handleConnectionFailure(e);
    }

    // ❌ ANTI-PATTERN 3: Exception for flow control
    public int parseOrDefault(String s) {
        try {
            return Integer.parseInt(s);
        } catch (NumberFormatException e) {
            return 0;  // This is fine - but only for this method
        }
        // Don't use exceptions for normal code paths (isEmpty etc.)
    }
    // ✅ Check first, parse after
    public int safeParse(String s, int defaultVal) {
        if (s == null || s.isBlank()) return defaultVal;
        try {
            return Integer.parseInt(s.trim());
        } catch (NumberFormatException e) {
            return defaultVal;
        }
    }

    // ❌ ANTI-PATTERN 4: Losing original exception (chaining without cause)
    try {
        dataBase.save(item);
    } catch (SQLException e) {
        throw new ServiceException("Failed to save");  // original cause LOST!
    }
    // ✅ Always pass cause in exception chaining
    try {
        dataBase.save(item);
    } catch (SQLException e) {
        throw new ServiceException("Failed to save item: " + item.getId(), e);  // cause preserved
    }
}

Quick Quiz

Tip

Tip

Practice Exception Best Practices in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Exception Best Practices

Practice Task

Note

Practice Task - (1) Write a working example of Exception Best Practices from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Exception Best Practices is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Topics in This Module

0/8 done