AlgoGalaxy

AlgoGalaxy

University
CodeRush
Jobs
Tools
Insights
Explore
Personalize
KotlinGoPHPRustGraphsArraysBit ManipulationDynamic ProgrammingGreedyHeapLinked ListStackStringsTreesTrieBacktrackingBinary SearchBSTComplexity AnalysisData Structures & Algorithms

Java | Exception Handling

Exception handling makes failure paths explicit. Good Java code separates expected recovery from programmer mistakes, preserves the original cause, releases resources deterministically and gives callers enough context to decide what to do next.

Checked and Unchecked Exceptions

Checked exceptions represent conditions a caller may reasonably recover from and must be declared or handled. Runtime exceptions usually signal invalid arguments, broken invariants or programming errors that should be prevented rather than routinely swallowed.

Catch Only What You Can Handle

A catch block should either recover, translate the failure into a domain-specific exception or add actionable context before rethrowing. Catching Exception broadly and continuing silently hides defects and corrupts normal control flow.

Finally and Try-With-Resources

finally runs after try and catch, but try-with-resources is the preferred way to close files, streams and database-style resources. It closes resources even when the body throws and preserves suppressed close failures.

Throw Versus Throws

throw creates an exception at the current point. throws documents that a method may propagate a checked exception. Use a precise exception type and a message that names the failed operation and relevant identifier.

Exception Boundaries

Validate at public boundaries, keep low-level causes available and convert infrastructure failures into domain language at service boundaries. This prevents SQL, IO or JSON details from leaking across an API contract.

Worked Examples

Example 1: Handle a Specific Parse Failure

Integer parsing can fail for malformed user input. Catch the precise NumberFormatException, return a safe result and leave unrelated runtime failures visible to the caller.

Code

public class Main {
    static int parsePort(String value) {
        try {
            int port = Integer.parseInt(value);
            if (port < 1 || port > 65535) {
                throw new IllegalArgumentException("Port is outside the valid range");
            }
            return port;
        } catch (NumberFormatException error) {
            System.out.println("Port must be a number");
            return -1;
        }
    }

    public static void main(String[] args) {
        System.out.println(parsePort("not-a-port"));
    }
}

Expected Result

Port must be a number
-1

Example 2: Close a File Safely

The BufferedReader is declared in the try-with-resources header. Java closes it automatically after the body finishes or fails, so the method does not need a fragile manual close inside finally.

Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class Main {
    static String firstLine(String source) throws IOException {
        try (BufferedReader reader = new BufferedReader(new StringReader(source))) {
            return reader.readLine();
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println(firstLine("AlgoGalaxy\nSecond line"));
        } catch (IOException error) {
            System.out.println("Read failed: " + error.getMessage());
        }
    }
}

Expected Result

AlgoGalaxy

Example 3: Create a Domain Exception

A domain exception gives callers language that matches the business rule. Keep the original cause when translating a lower-level failure so logging and diagnosis retain the real root problem.

Code

public class Main {
    static class InsufficientCreditsException extends Exception {
        InsufficientCreditsException(int requested, int available) {
            super("Requested " + requested + ", but only " + available + " credits remain");
        }
    }

    static void reserve(int requested, int available)
            throws InsufficientCreditsException {
        if (requested > available) {
            throw new InsufficientCreditsException(requested, available);
        }
    }

    public static void main(String[] args) {
        try {
            reserve(8, 5);
        } catch (InsufficientCreditsException error) {
            System.out.println(error.getMessage());
        }
    }
}

Expected Result

Requested 8, but only 5 credits remain

Example 4: Rethrow With Context

A service method adds the account identifier while preserving the cause. The caller sees a stable service-level message and diagnostic tools can still inspect the original IllegalStateException.

Code

public class Main {
    static String loadProfile(String accountId) {
        try {
            if (accountId.equals("missing")) {
                throw new IllegalStateException("profile row was not found");
            }
            return "profile:" + accountId;
        } catch (IllegalStateException cause) {
            throw new RuntimeException(
                "Unable to load profile for account " + accountId,
                cause
            );
        }
    }

    public static void main(String[] args) {
        try {
            loadProfile("missing");
        } catch (RuntimeException error) {
            System.out.println(error.getMessage());
            System.out.println(error.getCause().getMessage());
        }
    }
}

Expected Result

Unable to load profile for account missing
profile row was not found

Example 5: Make the input visible

Start by naming the value the next line depends on. This keeps the lesson input explicit before we apply a transformation or call an external boundary. We are applying that habit while revisiting Java Exception Handling.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        String lesson = "Java Exception Handling";
        System.out.println(lesson.toUpperCase());
    }
}

Expected Result

JAVA EXCEPTION HANDLING

Try next: Replace the sample value with one from your own notes, predict the result, and then run it.

Example 6: Make the input visible

Start by naming the value the next line depends on. This keeps the lesson input explicit before we apply a transformation or call an external boundary. We are applying that habit while revisiting Java Exception Handling.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        String lesson = "Java Exception Handling";
        System.out.println(lesson.toUpperCase());
    }
}

Expected Result

JAVA EXCEPTION HANDLING

Try next: Replace the sample value with one from your own notes, predict the result, and then run it.

Example 7: Guard an empty boundary

A small guard makes the allowed and rejected path visible. We want a caller to receive an intentional result instead of discovering an unexplained failure later. We are applying that habit while revisiting Java Exception Handling.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    static boolean accepted(String value) {
        return value != null && !value.isBlank();
    }

    public static void main(String[] args) {
        System.out.println(accepted("Java Exception Handling"));
    }
}

Expected Result

true

Try next: Try an empty value as well as the normal value and describe why the two outcomes differ.

Example 8: Keep the transformation pure

This step returns a value instead of mixing the rule with display or storage work. That separation gives us a small unit we can run, test, and reuse. We are applying that habit while revisiting Java Exception Handling.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    static int doubleValue(int value) { return value * 2; }

    public static void main(String[] args) {
        System.out.println(doubleValue(6));
    }
}

Expected Result

12

Try next: Call the same rule twice with different inputs and confirm that each result depends only on its input.

Example 9: Make a branch deliberate

Use a named branch where the business rule changes. A future reader should be able to point at the condition and state the result for both sides. We are applying that habit while revisiting Java Exception Handling.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        int score = 7;
        String result = score >= 5 ? "ready" : "review";
        System.out.println(result);
    }
}

Expected Result

ready

Try next: Change the boundary value by one and explain exactly which branch becomes active.

Example 10: Use a collection without hidden mutation

Collections become safer when we can see which value is read, which value is derived, and whether the original collection remains owned by the caller. We are applying that habit while revisiting Java Exception Handling.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> lessons = List.of("Java Exception Handling", "boundary");
        System.out.println(String.join(" | ", lessons));
    }
}

Expected Result

Java Exception Handling | boundary

Try next: Add one more item and predict the derived result before executing the code.

Example 11: Return a named outcome

A named outcome is easier to test than an implied side effect. We can now distinguish a successful path from a rejected path without guessing from console noise. We are applying that habit while revisiting Java Exception Handling.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    record Outcome(String status, String lesson) {}

    public static void main(String[] args) {
        Outcome outcome = new Outcome("ready", "Java Exception Handling");
        System.out.println(outcome.status());
    }
}

Expected Result

ready

Try next: Rename the outcome in your own words while preserving the same success and failure rule.

Example 12: Trace a small loop

Work through one value at a time. The point is not to memorize syntax; it is to see how the accumulator or output changes after each repeatable step. We are applying that habit while revisiting Java Exception Handling.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        int total = 0;
        for (int value : new int[] {1, 2, 3}) total += value;
        System.out.println(total);
    }
}

Expected Result

6

Try next: Use a shorter collection first, then add one value and trace the extra iteration aloud.

Example 13: Keep display at the edge

The core rule prepares a value, while the outer line decides how to show it. That keeps the result usable by a UI, test, API, or command-line caller. We are applying that habit while revisiting Java Exception Handling.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    static String display(String value) { return "Lesson: " + value; }

    public static void main(String[] args) {
        System.out.println(display("Java Exception Handling"));
    }
}

Expected Result

Lesson: Java Exception Handling

Try next: Change only the display text and verify that the underlying rule and result stay unchanged.

Example 14: Test the closest boundary

A useful example includes the nearest boundary, not only the happy path. We are making the behavior inspectable before a real caller relies on it. We are applying that habit while revisiting Java Exception Handling.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    static int quantity(int value) {
        if (value < 1) throw new IllegalArgumentException("quantity must be positive");
        return value;
    }

    public static void main(String[] args) {
        System.out.println(quantity(1));
    }
}

Expected Result

1

Try next: Try the lowest supported value and then one value just outside the accepted range.

Example 15: Write a tiny regression check

A compact assertion turns the lesson into a repeatable promise. It helps us catch a changed rule before a larger program hides the source of the mistake. We are applying that habit while revisiting Java Exception Handling.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        String result = "Java Exception Handling".toUpperCase();
        if (!result.equals("JAVA EXCEPTION HANDLING")) throw new AssertionError("contract failed");
        System.out.println("contract holds");
    }
}

Expected Result

contract holds

Try next: Deliberately change the expected value once, observe the failed check, and then restore the correct contract.

Complexity Analysis

Operation Complexity Explanation
Specific catch and recovery O(1) control overhead The meaningful work cost remains the underlying operation cost.
Try-with-resources O(1) resource-management overhead Close executes automatically as control leaves the block.
Exception propagation O(stack depth) worst case Runtime unwinds frames until a matching handler is found.

Common Mistakes

  • Catching Exception or Throwable when the code cannot make a safe recovery decision.
  • Using exceptions as ordinary branch control for expected high-frequency states.
  • Dropping the cause when translating an IO or persistence failure into a service exception.
  • Returning from finally, which can hide an exception thrown in try or catch.

Interview Checklist

  • Name whether a failure is checked, unchecked, recoverable or a caller-contract violation.
  • Use the narrowest catch type and explain the recovery or translation policy.
  • Prefer try-with-resources for every AutoCloseable resource boundary.
  • Test malformed input, a failing resource, a rethrown cause and a successful path.
logo of AlgoGalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

AlgoGalaxy University

University HomeTechnology LearningCoding ProblemsLearning ProgressCareer OpportunitiesTechnology InsightsUtilNexa ToolsAlgoGalaxy HomeContact Support

AlgoGalaxy CodeRush

CodeRush HomeProblem SetsProgress TrackerLearn TechnologyTechnology JobsEngineering InsightsDeveloper UtilitiesAlgoGalaxy HomePrivacy Policy
Privacy Policy

 • 

Terms of Service

Copyright © AlgoGalaxy 2026