Course contentsShow
← Java
Lesson 803 of 2,87019. Exception Hierarchy and Custom ExceptionsFree lesson

When to Use RuntimeException vs Checked Exceptions

Learn design principles for choosing between unchecked and checked exceptions in your APIs.

When to Use RuntimeException vs Checked Exceptions

What you'll learn: You'll learn the design principles that help you decide whether to throw a RuntimeException or a checked exception in your own APIs.

The Design Decision

When creating methods that throw exceptions, you face a critical choice: should you throw a checked exception (forcing callers to handle it) or a RuntimeException (letting it propagate freely)? This decision shapes how your API is used and how errors are communicated.

The Golden Rules

Use Checked Exceptions When:

  • The caller can reasonably recover from the problem
  • The exceptional condition is external to the program's logic (file not found, network timeout)
  • You want to force the caller to think about and handle the situation
  • The error is expected in normal operation scenarios

Example scenario: Reading a configuration file that might not exist—callers can provide defaults or prompt the user.

Use RuntimeException When:

  • The problem indicates a programming error (bug in the code)
  • The caller cannot reasonably recover without fixing their code
  • The error is due to violating a method's contract (null when non-null required, negative value when positive required)
  • Forcing checks would clutter code with defensive boilerplate

Example scenario: Passing null to a method that explicitly requires non-null—this is a bug the developer must fix.

The Practical Impact

Think of checked exceptions as roadblocks that say "stop and think about this problem." Think of RuntimeException as falling off a cliff when you've written buggy code—it shouldn't happen if your code is correct.

Key Takeaway: Use checked exceptions for recoverable, external failures that callers should handle; use RuntimeException for programming errors and violated preconditions that indicate bugs requiring code fixes.