Java
Throwable
Exception
Try-Catch
Programming Concepts

Java Throwable vs Exception in try-catch: which to catch

Codemia Knowledge Hub ·

Throwable catches everything: both Exception (recoverable problems) and Error (fatal JVM-level problems like OutOfMemoryError). Exception catches only the recoverable subset. In nearly all application code, catch Exception, or better, specific exception types. Reserve catch (Throwable) for top-level error handlers, shutdown hooks and thread pool tasks where you need to make sure a failure is never silently lost.

The Java exception hierarchy

text
1java.lang.Object
2  └── java.lang.Throwable
3        ├── java.lang.Exception
4        │     ├── java.lang.RuntimeException    (unchecked)
5        │     │     ├── NullPointerException
6        │     │     ├── IllegalArgumentException
7        │     │     ├── IndexOutOfBoundsException
8        │     │     └── ...
9        │     ├── IOException                   (checked)
10        │     ├── SQLException                  (checked)
11        │     └── ...
12        └── java.lang.Error
13              ├── OutOfMemoryError
14              ├── StackOverflowError
15              ├── VirtualMachineError
16              ├── NoClassDefFoundError
17              └── ...

A catch clause matches the named type and all of its subclasses. Catching Throwable matches the whole tree. Catching Exception matches everything except the Error branch.

Catching Exception in application code

Exception covers the problems application code is expected to handle: checked exceptions (I/O failures, network errors, parse errors) and unchecked runtime exceptions (null references, illegal arguments, array bounds violations).

java
1public User loadUser(String id) {
2    try {
3        String json = httpClient.get("/users/" + id);
4        return objectMapper.readValue(json, User.class);
5    } catch (IOException e) {
6        // Network or parsing failure - recoverable
7        log.warn("Failed to load user {}: {}", id, e.getMessage());
8        return User.defaultUser();
9    } catch (Exception e) {
10        // Catch-all for unexpected runtime exceptions
11        log.error("Unexpected error loading user {}", id, e);
12        throw new ServiceException("User load failed", e);
13    }
14}

This catches the expected exception first (IOException), then uses a broader Exception catch as a safety net. It is the recommended approach for most application code.

When catching Throwable is justified

Catching Throwable includes Error subtypes, which represent conditions the JVM considers unrecoverable:

Error TypeMeaningShould you catch it?
OutOfMemoryErrorJVM heap is exhaustedAlmost never (state is corrupted)
StackOverflowErrorCall stack exceededRarely (indicates infinite recursion)
NoClassDefFoundErrorRequired class missing at runtimeSometimes (classpath issues in plugins)
VirtualMachineErrorJVM itself is failingNever (JVM is dying)
AssertionErrorAssertion failedRarely (indicates logic bugs)
LinkageErrorClass loading/linking failureSometimes (in classloader-heavy systems)

The legitimate reasons are narrow.

1. Tasks submitted to a thread pool

java
1ExecutorService executor = Executors.newFixedThreadPool(4);
2executor.submit(() -> {
3    try {
4        processTask();
5    } catch (Throwable t) {
6        // Without this, the error is stored in the Future and never seen unless someone calls get()
7        log.error("Task failed with unrecoverable error", t);
8        // Do NOT try to "recover" - just log and let the thread return
9    }
10});

When a task is passed to submit(), anything it throws, including an OutOfMemoryError, is stored in the returned Future. If nobody calls Future.get(), the failure is invisible. Catching Throwable inside the task makes sure it is at least logged.

2. Shutdown hooks

java
1Runtime.getRuntime().addShutdownHook(new Thread(() -> {
2    try {
3        gracefulShutdown();
4    } catch (Throwable t) {
5        // Log but do not rethrow - this is the last chance to record the error
6        System.err.println("Shutdown hook failed: " + t.getMessage());
7    }
8}));

3. Plugin or classloader isolation boundaries

java
1public Object invokePlugin(String className, Object input) {
2    try {
3        Class<?> pluginClass = pluginClassLoader.loadClass(className);
4        Method method = pluginClass.getMethod("process", Object.class);
5        return method.invoke(pluginClass.getDeclaredConstructor().newInstance(), input);
6    } catch (Throwable t) {
7        // Plugin classloader issues can throw NoClassDefFoundError, LinkageError
8        log.error("Plugin {} failed", className, t);
9        return null;
10    }
11}

Side-by-side comparison

java
1// Catching Exception - standard application code
2try {
3    riskyOperation();
4} catch (Exception e) {
5    log.error("Operation failed", e);
6    // Can recover, retry, or fail gracefully
7    // Does NOT catch Error subtypes
8}
9
10// Catching Throwable - top-level safety net
11try {
12    riskyOperation();
13} catch (Throwable t) {
14    log.error("Operation failed with potentially fatal error", t);
15    // Catches EVERYTHING including OutOfMemoryError, StackOverflowError
16    // Recovery may not be possible - state could be corrupted
17}
Aspectcatch (Throwable t)catch (Exception e)
Catches checked exceptionsYesYes
Catches runtime exceptionsYesYes
Catches Error subtypesYesNo
Typical use caseFramework-level error handlingApplication-level error handling
Recovery expectationLow (log and fail)High (handle and continue)
Risk of masking fatal errorsHighLow
Best practice recommendationOnly at thread/process boundariesPreferred for business logic

Prefer catching specific exceptions

Both catch (Throwable) and catch (Exception) are broad. Usually you should catch the most specific type you expect.

java
1// Best: catch exactly what you expect
2try {
3    Path path = Path.of(filename);
4    String content = Files.readString(path);
5    return objectMapper.readValue(content, Config.class);
6} catch (NoSuchFileException e) {
7    log.info("Config file not found, using defaults");
8    return Config.defaults();
9} catch (JsonProcessingException e) {
10    throw new ConfigException("Invalid config format in " + filename, e);
11} catch (IOException e) {
12    throw new ConfigException("Failed to read config file " + filename, e);
13}
14
15// Acceptable: broad catch with re-throw of unknowns
16try {
17    complexOperation();
18} catch (SpecificBusinessException e) {
19    handleBusinessError(e);
20} catch (Exception e) {
21    // Log and re-throw - do not silently swallow
22    log.error("Unexpected exception in complexOperation", e);
23    throw e;
24}

Multi-catch (Java 7+)

Multi-catch, introduced in Java 7, lets you handle several specific exceptions the same way without catching a broad type:

java
1try {
2    parseAndStore(input);
3} catch (NumberFormatException | DateTimeParseException | JsonParseException e) {
4    // Handle all parsing failures the same way
5    log.warn("Invalid input format: {}", e.getMessage());
6    return ValidationResult.invalid(e.getMessage());
7}

This beats catch (Exception e) because it documents which exceptions you expect and does not accidentally catch ones you did not anticipate.

What catching OutOfMemoryError actually does

Catching an OutOfMemoryError does not free memory. The application's state is likely corrupted: collections may be partially populated, transactions half-committed, and locks held indefinitely. The thread keeps running, but the application is unreliable.

java
1// This is dangerous - the application may be in a corrupt state
2try {
3    List<byte[]> data = new ArrayList<>();
4    while (true) {
5        data.add(new byte[1_000_000]); // Allocate until OOM
6    }
7} catch (OutOfMemoryError e) {
8    // The list is partially populated, GC is under severe pressure
9    // Any subsequent allocation might trigger another OOM
10    log.error("Out of memory", e);
11    // "Recovering" here is unreliable
12}

The safe pattern is to catch it only at the outermost level (for example in a thread pool's error handler), log it, and shut down the application or reject the current request.

Mistakes with broad catches

  • Catching Throwable in application code and swallowing it. This hides fatal JVM problems like OutOfMemoryError, and the application continues in a corrupt state, producing wrong results or deadlocking. Always re-throw or terminate after catching Throwable.
  • Catching Exception and silently returning null. Log even recoverable exceptions. A silent null pushes the failure downstream, where it surfaces as a NullPointerException with no hint of the root cause.
  • Catching Error to "recover" from it. StackOverflowError and OutOfMemoryError mean fundamental resources are exhausted, and recovery code is likely to trigger the same error. Catch them only for logging and shutdown.
  • Using catch (Exception e) when you know the specific exceptions. Broad catches swallow unexpected exceptions and hide bugs. Catch the narrowest type possible.
  • Ordering catch clauses wrongly. Catch clauses are evaluated in order, so catching Exception before a subtype makes the specific block unreachable. The compiler flags this, but it is an easy mistake during refactoring.
  • Dropping the original exception when re-throwing. Always chain: throw new ServiceException("message", e). Losing the cause makes debugging nearly impossible.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms