BairesDev

Checked vs Unchecked Exceptions: Which Failures Should Callers Handle?

Learn how to choose between checked and unchecked exceptions based on who owns recovery, retry logic, and the final failure response.

Last updated:
17 min read
Verified Top Talent

By Glesio Paiva

Software Engineer21 Years of Experience

Glesio is a senior software engineer with 20+ years of experience in Java and enterprise system architecture. He has built high-performance solutions for government systems and fintech platforms, including work with Ame Digital. Glesio holds a Master's degree in Computer Science from UFSCar.

Abstract illustration representing checked and unchecked exceptions, featuring highlighted software components, layered execution paths, and connected error propagation flows.

For me, choosing an exception superclass starts with what the caller can safely do after a failure. If a selected file disappears, an import controller might ask the user to choose another. When checkout has no fallback, a shared API handler might instead report that inventory is unavailable. The contract should give the code responsible for either response enough information to act, while letting intervening methods pass the failure along when they have no useful action to take.

Key Points

  • Your checked declaration satisfies the compiler but guarantees nothing about whether the caller can actually recover.
  • Your immediate caller may have no useful response, so design the contract for the layer that does.
  • Spring’s DataAccessException is unchecked but includes recoverable branches your team still needs to evaluate before retrying.
  • Decide who owns the final response before you choose an exception type or assign retry responsibility.

What Is the Difference Between Checked and Unchecked Exceptions?

I keep the categories straight in Java programming by focusing on what the compiler requires. Exceptions in Java fall into two main categories: checked and unchecked. For checked exceptions, Java requires catching the exception or declaring it with the throws keyword; unchecked exceptions can propagate without either step. That obligation is enforced at compile time, but both kinds of exception occur during program execution.

Under the JLS, Throwable is the root of the hierarchy and its direct subclasses are Exception and Error. Error and RuntimeException, along with their subclasses, are unchecked. All other exception classes, including Throwable itself, are checked. In practice, checked exceptions such as IOException extend Exception without extending RuntimeException, while the unchecked exceptions developers typically work with, such as NullPointerException and IllegalArgumentException, extend the RuntimeException class. For application-defined exceptions in Java, that usually means extending Exception for a checked type or RuntimeException for an unchecked type. Each custom exception class should say what failed in the caller’s terms.

Code can throw exceptions of either kind. When that happens, normal flow of the program stops as Java looks for a matching catch clause naming that exception’s class or a superclass. If none is found, uncaught-exception handling runs before the current thread terminates.

Under the Java Language Specification’s checking rules, calling a method that declares IOException requires catching it or giving your method a compatible throws declaration. That declaration satisfies the compiler’s compile-time obligation by passing responsibility upward, but supplies no recovery action. Two compile-time behaviors are worth knowing here. First, catching a checked exception that the try block can never throw is a compile error, with the exception of catch clauses for Exception or Throwable, which the compiler always permits. Second, Java 7 introduced precise rethrow: if you catch (Exception e), log it, and rethrow e without modification, the compiler can verify which specific checked types actually leave the block, so your method only needs to declare those specific types rather than Exception. The design choice is whether the compiler obligation helps the caller.

Error and its subclasses are also unchecked, but represent serious failures outside normal application exception handling. Checked exceptions are verified by the compiler, while unchecked exceptions only surface at runtime. Unchecked exceptions usually signal programmer mistakes or logic errors, such as a null reference or an invalid index.

This short method shows both kinds: the compiler forces the file read to be handled, while the array index fails only at runtime.

Code
1public static void main(String[] args) {
2    try (BufferedReader reader = new BufferedReader(new FileReader(args[0]))) {
3        System.out.println(reader.readLine());
4    } catch (IOException e) { // checked: handled here or declared with throws
5        System.out.println("Cannot read file: " + e.getMessage());
6    }
7    int[] values = new int[2];
8    // values[5] = 1; would compile but throw ArrayIndexOutOfBoundsException at runtime
9}

Why Does the Debate About Exceptions in Java Never Settle?

Oracle’s Java tutorial recommends checked exceptions when a client can reasonably be expected to recover, a principle Bloch reinforces in Effective Java (3rd ed., Items 70 and 71): use checked exceptions for conditions from which the caller can recover, and avoid imposing them when callers have no useful action to take. Applying that advice requires identifying the client and its next action, which becomes harder when the failure originates below the layer where anyone can respond usefully.

Consider an inventory API that exposes SQLException to checkout. Checkout must acknowledge a database failure even though its concern is whether it can reserve the items, and it may have no useful response to a driver-specific error. If inventory later moves behind a remote service, those exposed exceptions may change while checkout’s decision stays the same.

That change can reach caller source code because checked declarations form part of the method contract. Adding a checked exception may require edits unless existing handlers or declarations already cover it. The interruption is useful when callers need to consider a new failure, but less useful when the new exception only reflects a changed implementation detail they cannot act on. Mandatory catch-or-declare code also adds verbosity as exceptions cross layers.

Using only unchecked exceptions in your own code removes the compiler obligation without resolving that design problem, and it’s not worth adopting as a blanket policy. Decide what callers can safely do with the failure, then whether requiring them to acknowledge it helps them choose that response.

What Actually Makes a Failure Recoverable?

Suppose a user selects an invoice file, but it no longer exists at the selected file path when the application tries to open it. The import controller can explain what happened and ask for another selection, giving the user a way forward. That response gives you a concrete reason to expose the failure through the import API.

The file-reading helper can’t offer the user that choice, and the import service directly above it may have no user interaction either. Both can pass the failure toward the controller. When the controller opens the file, it’ll catch a NoSuchFileException (the NIO subclass of IOException) or a FileNotFoundException from java.io depending on which API the helper uses. You can’t avoid this exception path with a Files.exists() pre-check: the file can disappear between that check and the actual open, so the exception handler is still required. A try-with-resources block keeps the resource cleanup reliable:

Code
1try (InputStream in = Files.newInputStream(path)) {
2    importService.load(in);
3} catch (NoSuchFileException e) {
4    ui.reportMissing(path);
5}

The enclosing method still declares throws IOException, so other I/O failures keep propagating to a handler that can respond. Compatible checked declarations support this arrangement without requiring recovery in the immediate caller. The try-with-resources statement handles the file close on both the success and failure paths without a catch block, which fits this pattern well: the helper releases the resource without owning any response. If close() itself throws, that exception is attached to the primary one as a suppressed exception, accessible via Throwable.getSuppressed(), so nothing is silently lost.

Now put the same file read in startup code loading mandatory configuration. Without valid configuration, there may be no safe way to continue, so stopping startup and reporting the problem to the system operator is appropriate. Catching IOException doesn’t create the fallback that this situation lacks. Wrap it instead and let startup fail immediately with a clear message: throw new UncheckedIOException(“Cannot load required config: ” + path, e), or throw new IllegalStateException(“Cannot load required config: ” + path, e) if you want a more general type. Either stops the process, surfaces the original stack trace, and tells whoever is reading the logs exactly what went wrong and where.

I’d ask “which caller can do what next?” and then examine what makes that action safe. Asking for another invoice file is straightforward before any invoices have been written. After a partial import, the same suggestion needs a plan for the completed work, or the user’s next attempt may repeat it.

How Do Checked and Unchecked Exceptions Compare?

The table separates language rules from design guidance. Neither exception category tells you whether retrying, falling back, or rejecting an operation is appropriate.

Dimension Checked exceptions Unchecked exceptions
Compiler enforcement Catch or declare when exception analysis requires it No catch-or-declare requirement
Intended failure type Named failures callers should explicitly address Programming errors (broken preconditions, bugs) and failures no immediate caller can act on, handled centrally
Caller responsibility Handle or declare for an upstream caller Handle where useful; document anticipated failures
API implications Checked declarations form part of the method contract Meaningful types communicate failures without mandatory declarations
Propagation Escaping checked exceptions need compatible declarations Propagate without declarations
Maintainability New types may require caller edits unless already covered Avoid declaration changes; still need discoverable failure contracts
Appropriate use cases Resource APIs or domain APIs requiring caller acknowledgment Broken preconditions, centralized handling without useful declarations, Spring data access
Examples IOException and SQLException IllegalArgumentException, NullPointerException, ArithmeticException, and DataAccessException

Where Do Checked and Unchecked Exceptions Belong?

How should external resource failures be exposed?

If an API’s purpose is to work with files, it makes sense to report file failures directly. A file utility might declare IOException, for example. An invoice importer may serve its caller better by reporting “source unreadable.” The caller can then respond to the import problem without tying its code to the importer’s storage provider.

Spring provides a similar way to separate database details from the code that handles a failure. JDBC’s SQLException is checked, while Spring’s DataAccessException gives callers a family of unchecked exception types that work across different data-access APIs. That family includes TransientDataAccessException, RecoverableDataAccessException and NonTransientDataAccessException, all extending DataAccessException. The translation happens through Spring’s SQLExceptionTranslator, applied automatically by JdbcTemplate and to @Repository beans via PersistenceExceptionTranslationPostProcessor. Even so, neither a transient nor a recoverable label tells your team whether a particular transaction is safe to retry. Before retrying, check what the operation already completed and what would happen if you repeated it.

If you’re using Spring, I’d start with the exception types it provides. Give a failure an application-specific name when that helps callers decide what to do next. The new exception can still be unchecked. I’d choose a checked exception when making callers catch or declare that failure helps them plan a useful response.

How should validation and domain rules differ?

An invalid date in an uploaded invoice is something the user can fix. I’d return a validation result that identifies the row, field, and problem, perhaps including a string describing the exact constraint violated, and report the mistakes together so the user can correct them in one pass.

Two cases apply here. First, developer error: when your code passes an argument that breaks a method’s documented contract, that’s a bug in the calling code. IllegalArgumentException signals exactly that violation, and the fix belongs in the caller. Second, user error: when a user submits bad input, that’s not a broken contract between your methods. Return the validation result described above so the user can correct it. Letting user-input problems bubble up as an IllegalArgumentException risks a 500 response where a clear validation message belongs.

If an importer dereferences a null reference, the JVM throws NullPointerException. Code can also fail fast deliberately with Objects.requireNonNull(x, “x must not be null”), which makes the problem visible at the entry point rather than somewhere deeper. Since Java 15, helpful NPE messages (JEP 358, on by default) name exactly which variable was null, which makes tracing how the caller supplied the null considerably faster. Integer division by zero can raise ArithmeticException, while an invalid index can trigger IndexOutOfBoundsException or a subclass. Check how the importer calculated those values. If the calculation is wrong, fix the code that produced it. Asking the user to upload again won’t repair that calculation.

Before choosing an exception type, I’d ask whether this outcome needs an exception at all. If the same invoice has already been imported, the API could return the existing import result without importing it again. If callers need to distinguish a new import from an existing one, return that information explicitly. Sealed types arrived in Java 17 and pattern matching for switch became final in Java 21, so on Java 21 or later a sealed interface makes this compiler-checked without any exception at all:

Code
1sealed interface ImportResult permits Imported, AlreadyImported, Rejected {}
2record Imported(String importId) implements ImportResult {}
3record AlreadyImported(String existingId) implements ImportResult {}
4record Rejected(String reason) implements ImportResult {}

Callers consume it with a switch pattern match, and the compiler rejects any switch that omits a permitted subtype, which gives you exhaustiveness checking without using an exception for an expected outcome.

How Should I Handle InterruptedException?

Never swallow it silently. If your code catches InterruptedException and does nothing, the thread’s interrupted status is cleared and callers have no way to know the interruption happened. Either restore the flag with Thread.currentThread().interrupt() so callers can check it, or let the exception propagate by declaring it in your method signature. Which you choose depends on whether your method can be interrupted safely mid-operation.

Should I Catch Exception or Throwable?

Catching Exception also catches every RuntimeException, which means programming errors like NullPointerException get swallowed alongside failures you actually expected. Catching Throwable goes further and catches Errors like OutOfMemoryError, which the JVM throws when it runs out of memory or conditions are otherwise severe enough that you generally can’t recover safely. If you need to handle multiple specific checked exceptions, multi-catch syntax keeps it clean: catch (IOException | SQLException e) handles each type explicitly without hiding unrelated failures behind a broad superclass.

What changes at a service boundary?

When another application or external system calls your service over HTTP, it receives a response, not your Java throws clause. RFC 9457 (Problem Details for HTTP APIs, which supersedes RFC 7807) defines a standard response body with fields including type, title, status, detail and instance, plus extension fields for things like an application-specific error code the calling system can match programmatically. Spring 6 supports this natively: ProblemDetail and ResponseEntityExceptionHandler let you map exceptions to structured responses without writing a custom serializer. For the inventory example, a @RestControllerAdvice can catch InventoryStoreUnavailableException and return a 503 ProblemDetail with a stable type URI and a detail message, while keeping the underlying storage exception in your server logs rather than the response body. Keep stack traces and storage failure details on the server so developers can investigate without exposing those implementation details to the calling system.

Your service may also call other services, where it needs a plan for getting no response at all. Suppose a payment provider accepts a charge, but your application times out before receiving the response. The application doesn’t know whether the charge went through, and retrying could charge twice. I’d let the code that understands the payment operation decide what happens next. It could use idempotency to prevent a repeat charge or reconciliation to establish what happened before proceeding. A “transient” exception and a retry limit don’t establish whether the original charge succeeded or make another attempt safe.

How Should Handling Exceptions Work Across Layers?

Return to the inventory API, and suppose its database connection is unavailable. The repository could translate that failure into an application-defined InventoryStoreUnavailableException, retaining the storage exception as its cause. Checkout would then receive a failure expressed in inventory terms while the original diagnostic information remained available.

For that translation to help, the new type must accurately describe what happened. If you’re wrapping an IOException in a layer where callers can’t recover from it, prefer java.io.UncheckedIOException (available since Java 8) over a bare RuntimeException: catch (IOException e) { throw new UncheckedIOException(e); }. This tells callers exactly what kind of failure propagated, which matters when they’re deciding whether to log, retry, or escalate. A malformed query or constraint violation isn’t automatically an availability problem, and labeling it “store unavailable” when either of those occurs could encourage a retry when the failure needs a code or data correction. Translate the specific failure you can identify rather than assigning every database exception the same meaning.

Preserving the cause lets that more useful public description coexist with the underlying explanation. The Java Throwable documentation describes wrapping for this purpose across abstraction layers. A constructor that passes message and cause to its superclass retains the original exception and its trace for investigation. Here’s what that looks like in practice:

Code
1public class InventoryStoreUnavailableException extends RuntimeException {
2    public InventoryStoreUnavailableException(String message, Throwable cause) {
3        super(message, cause);
4    }
5}

The try-catch block that translates the failure and preserves the cause:

Code
1// Correct: cause is preserved for investigation
2try {
3    return inventoryRepository.findAvailable(itemId);
4} catch (DataAccessException e) {
5    throw new InventoryStoreUnavailableException("Inventory store unavailable", e);
6}
7
8
9// Anti-pattern: cause is lost, stack trace from the original failure disappears
10try {
11    return inventoryRepository.findAvailable(itemId);
12} catch (DataAccessException e) {
13    throw new InventoryStoreUnavailableException(e.getMessage(), null);
14}

Once the failure has the right meaning, let it travel. Handling exceptions at the layer that owns the response avoids long catch-and-rethrow chains. If checkout has no fallback and the shared API handler owns the response, I’d use a meaningful unchecked type here. Requiring declarations in the intervening methods wouldn’t improve checkout’s response. Wrapping it again at every service method can preserve the cause, but adds little when none of those wrappers explains anything new. Keep try-catch blocks out of intervening methods when they add no distinct action or information. Also avoid deeply nested try-catch blocks, which make the failure path hard to read.

At the edge, the handler can map the failure to the agreed response and record the context needed to investigate it. I’d make this the primary recording point in this example, adding lower-layer logs when they contribute distinct information. Three copies of the same failure don’t explain it three times better.

The handler can own the response while lower layers still release resources they opened. A file-reading helper can close its file without deciding which file the user should choose next.

When Should You Use Checked vs Unchecked Exceptions?

For a new API, I’d write the caller’s failure path, sketching which try-catch block will own the response, before choosing the exception superclass. Describe the failure in the caller’s terms, then follow it to the code that can respond. This exposes whether the proposed contract gives someone a useful choice or just passes technical details through a chain of methods.

When a shared boundary handler already owns the response and declarations add no useful caller decision, I’d default to a meaningful unchecked exception. Change that choice when the API should require callers to address a named failure, through handling or an upstream declaration. If the outcome is instead an expected branch in normal processing, start with an explicit result so the caller can work with it directly.

Test the response you’ve chosen against the failure that justified it. For the importer, check what the user sees and what remains after partial work. For inventory, verify that translation retains the cause without misclassifying unrelated storage failures. For payments, test an unknown original outcome rather than assuming the charge failed.

Use those examples to document your team’s Java programming standards for translation, retries, and logging. When evaluating Java development services, ask prospective partners to walk through both a successful operation and a failed one. Establish who chooses the response, what information they have, and why the action is safe.

Key Takeaways

  • Start with the caller’s response, then choose how the API expresses the failure.
  • Use checked exceptions when deliberate caller acknowledgment improves the contract; recovery can happen upstream.
  • Use meaningful unchecked types when shared handling owns the response and declarations add no useful decision; consider explicit results for expected branches.
  • Translate where meaning changes, preserve causes, and test retries and partial completion.

Frequently Asked Questions

  • Are all runtime exceptions unchecked exceptions?

    Yes. RuntimeException and all its subclasses are unchecked but they’re not the whole category. Error and its subclasses are unchecked too and represent serious failures your application normally shouldn’t try to catch.

  • Can you convert a checked exception into an unchecked exception?

    Yes. Catch the checked exception and wrap it in a RuntimeException or a suitable custom subclass. You’re creating a new object, not changing the original, so pass the original as the cause through a constructor that preserves it. Pick the new type based on what your caller actually needs to know about the failure at their level of the API.

  • Does using throws affect exception-handling performance?

    A throws declaration doesn’t construct or throw anything on its own, so it has no direct performance cost. If you want to measure exception-handling overhead, look at what the failure path actually does. Construction is usually the expensive part because new Throwable objects capture stack traces. Rethrowing the same object doesn’t refill the trace or add a frame, so your measurement should reflect what your path actually does.

  • What does Java check at compile time for checked exceptions?

    When Java’s exception analysis determines that your method can throw a checked exception, you must either catch it or declare it in a throws clause. That clause can name a superclass so you don’t have to list every subtype separately. One constraint worth knowing: an overriding method can’t declare checked exceptions the overridden method doesn’t already permit. The compiler verifies all of this but it can’t tell you whether your catch block actually recovers from anything.

  • How should teams standardize exception policies across services?

    Start with a few real failed operations and trace each one to the code that actually owns the response. Use those examples to agree on a failure vocabulary, where translation happens, how causes get preserved, and who owns retries and logging. For remote APIs, capture that contract in error identifiers and response schemas that are separate from your internal Java exception classes. That way your team’s services can use their own framework hierarchies without leaking implementation details to clients.

By Glesio Paiva

Software Engineer21 Years of Experience

Glesio is a senior software engineer with 20+ years of experience in Java and enterprise system architecture. He has built high-performance solutions for government systems and fintech platforms, including work with Ame Digital. Glesio holds a Master's degree in Computer Science from UFSCar.