Practice Exception Handling in Java

Handle errors gracefully using try-catch, throw, and custom exceptions.

Work through 24 exercises with starter code, expected output, test cases, and hints.

How to learn Exception Handling

An exception reports that a method could not complete its contract normally. Catch an exception only where the program can add context, recover, translate it to a more suitable abstraction, or perform boundary-level reporting. Catching and ignoring it makes the program harder to diagnose.

Checked exceptions must be caught or declared; unchecked exceptions do not have that compiler requirement. That distinction does not decide whether an error is important. It describes how the API communicates the failure to callers.

Recommended learning order

  1. Read the failure: Inspect the exception type, message, cause, and first relevant stack frame before changing code.
  2. Catch narrowly: Wrap only the statements expected to fail and catch the most specific type you can handle.
  3. Preserve resources and causes: Use try-with-resources for AutoCloseable values and retain the original exception when translating failures.
  4. Design exception contracts: Validate method inputs, document expected failures, and create a custom exception only when it adds a meaningful domain distinction.

Tested example: Translate a parsing failure with its cause

The boundary method gives callers a useful domain message while retaining NumberFormatException as the cause for debugging. It does not catch unrelated failures.

public class Main {
    static int positiveCount(String text) {
        try {
            int value = Integer.parseInt(text);
            if (value < 0) throw new IllegalArgumentException("count must not be negative");
            return value;
        } catch (NumberFormatException cause) {
            throw new IllegalArgumentException("count must be an integer", cause);
        }
    }

    public static void main(String[] args) {
        try {
            positiveCount("four");
        } catch (IllegalArgumentException error) {
            System.out.println(error.getMessage());
            System.out.println(error.getCause().getClass().getSimpleName());
        }
    }
}

Expected output

count must be an integer
NumberFormatException

Change and run this example in the Java compiler

Common mistakes

  • Catching Exception around a large block, which hides which operation was expected to fail.
  • Logging an exception and rethrowing it at every layer, producing duplicate noise without new context.
  • Returning from finally or throwing a new failure there, which can suppress the original result or exception.
  • Using exceptions as ordinary loop or branch control when a direct condition would express the expected case.

How to practice

Start with one catch, then multiple specific catches, finally, try-with-resources, and custom exceptions. In each answer, identify who can recover and whether the original cause remains available.

Exercises to do first

  • Basic try-catch — Handle one expected failure at the smallest useful boundary.
  • Try with resources — Let Java close an AutoCloseable resource on success or failure.
  • Custom exception — Create a domain-specific failure only where it clarifies the caller contract.

Exception Handling exercises

  1. Basic Try-Catch Java exercise — Handle a simple exception
  2. Multiple Catch Blocks Java exercise — Handle different exception types
  3. Using Finally Block Java exercise — Execute cleanup code with finally
  4. Throwing Exceptions Java exercise — Manually throw an exception
  5. Using Throws Clause Java exercise — Declare exceptions in method signature
  6. Try-With-Resources Java exercise — Automatic resource management
  7. Custom Exception Class Java exercise — Create and use custom exception
  8. Input Validation with Exceptions Java exercise — Validate user input using exceptions
  9. Exception Chaining Java exercise — Chain exceptions to preserve cause
  10. Retry with Exceptions Java exercise — Implement retry logic for failures
  11. Exception Propagation Java exercise — Understand exception propagation through call stack
  12. Age Range Validator Java exercise — Validate age is within acceptable range
  13. Password Validation Java exercise — Validate password against multiple rules
  14. Null Handling Java exercise — Handle NullPointerException gracefully
  15. Resource Cleanup Pattern Java exercise — Ensure resources are cleaned up
  16. Exception Logging Java exercise — Log exception details properly
  17. Retry Mechanism Java exercise — Implement automatic retry on failure
  18. Age Input Validation with Exceptions Java exercise — Validate user input using exceptions
  19. Aggregate Multiple Exceptions Java exercise — Collect and report multiple validation errors
  20. Graceful Degradation Java exercise — Provide fallback when operation fails
  21. Exception Chaining Java exercise — Chain exceptions to preserve root cause
  22. Custom AutoCloseable Java exercise — Create a resource that auto-closes
  23. Suppressed Exceptions Java exercise — Handle exceptions during close()
  24. Validation with Exceptions Java exercise — Validate input and throw appropriate exceptions

Browse the complete Java practice path · Open the online Java compiler