Skip to content
Tutorials Center
My learning

Topics

Lesson 81 of 134 ยท Error Handling and Resources

Custom Exceptions and Error Design

Learn to design Kotlin error handling - custom exception classes, sealed exception hierarchies, wrapping causes, translating errors between layers, and choosing exceptions or sealed results.

You already know how to throw and catch exceptions. The harder question is what the errors of your own program should look like. Should a failed payment be an exception or a return value? How many exception classes do you need? What should a caller be able to learn from one? Good answers make code that is easy to use correctly and easy to debug at 2 a.m.; poor answers give you a thousand catch (e: Exception) blocks and logs that say only Something went wrong.

This lesson is about design. We start with writing a custom exception class, then build hierarchies, then discuss wrapping causes across layers, and finish with how exceptions compare to sealed results (the choice you will make most often in real projects).

Writing a custom exception

A custom exception is a class that extends Exception (or RuntimeException, which in Kotlin is just as unchecked, since Kotlin has no checked exceptions). The minimum is a class with a message:

Kotlin A first custom exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The class does two jobs. Its message is for humans reading logs. Its properties (item, requested, available) are for code: the handler can compute the shortfall or offer to reorder without parsing text. When you design an exception, ask "what would the caller need to react?" and make that data part of the class.

A few conventions:

  • Name it for the problem, end with Exception: OutOfStockException, ConfigurationException. Avoid names like MyException.
  • Extend the closest standard type. A bad argument? IllegalArgumentException. A wrong state? IllegalStateException. Otherwise Exception (or RuntimeException).
  • Offer a cause parameter for exceptions that wrap lower-level failures (below).
  • Do not extend Throwable or Error directly. Error is for conditions a program should not try to handle.

Hierarchies: one root, a few branches

When a library or module can fail in several ways, give it a base exception and let specific failures extend it. Callers can then catch the whole family with one clause or react to one case.

Kotlin An exception hierarchy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The most specific catch comes first (InsufficientFundsException), then the family (BankException), exactly like the order rule in Exceptions. Anything that is not a BankException, such as a NullPointerException from a bug, passes through untouched, which is what you want: a bug should not be reported as "refused".

Seal the hierarchy when it is closed

If the set of failures is fixed, make the base class sealed. Then when over the exception type is checked for completeness by the compiler:

Kotlin A sealed exception hierarchy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Add a new subclass to ParseException and explain stops compiling until you handle it. That is the benefit of sealing; the cost is that outside code (other modules) cannot add its own subclasses.

Keep hierarchies shallow. One root with five or six direct subclasses is common; five levels deep is a sign you are classifying instead of designing for the handler. Ask: is there code that will catch this class on its own? If not, a property or message might be enough, instead of a new class.

Wrapping: keep the cause, change the level

Lower layers fail in their own vocabulary (SQLException, FileNotFoundException, NumberFormatException). Higher layers should speak in terms of their own domain, otherwise callers must know about every detail you use internally, and changing the database breaks every catch. The fix is to translate at the boundary and keep the original as the cause.

Kotlin Wrapping low-level failures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

When this exception is logged with its stack trace, you see both stories: the ConfigException first, and below it Caused by: java.lang.NumberFormatException: For input string: "80x" with its own trace. That chain is exactly what you need to debug, so always pass the cause when you wrap. Throwing a new exception without the cause throws away the evidence.

Walking the chain in code is a simple loop over cause, and generateSequence expresses it neatly:

Kotlin Walking the cause chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

(That java.io.IOException is a checked exception in Java, and Kotlin does not mind: you can create and throw it with no throws clause anywhere.)

Where do you translate? At module and layer boundaries: where the repository meets the service, where your library meets the application. Inside a module, let exceptions flow freely. Do not wrap at every function, or you get a pile of identical Caused by entries.

Exceptions or sealed results?

Exceptions are for situations the immediate caller probably cannot or should not handle: they propagate upward until some layer that knows what to do. For failures that are a normal part of the operation, a returned value is often clearer:

Kotlin
// read-only example: failures as part of the return type
sealed interface Withdrawal {
    data class Done(val newBalance: Int) : Withdrawal
    data class Refused(val reason: String) : Withdrawal
}

fun withdraw(account: Account, amount: Int): Withdrawal { /* ... */ TODO() }

Compare the two styles:

Exceptions Sealed result
Caller must handle it? No, nothing forces it Yes, when must be exhaustive
Visible in the signature? No Yes
Travels across many layers cheaply to code that can handle it Yes No, each layer must pass it on
Best for Bugs, system failures (disk, network), "this should not happen here" Business outcomes callers expect: "invalid", "not found", "declined"
Cost Building a stack trace, slow in hot loops Allocation of a small object

A useful rule of thumb: expected outcomes are values, unexpected problems are exceptions. "The card was declined" is a value; "the payment service returned malformed JSON" is an exception. Mix them freely: a function may return a sealed result for domain outcomes and still throw for bugs. See The Result Type and Sealed Classes and Interfaces for the value side.

Exceptions as control flow

Using exceptions to jump out of deeply nested code can be legitimate, but the stack-trace capture is the expensive part. For an exception that is used purely as a signal, you can skip it by overriding fillInStackTrace:

Kotlin A cheap control-flow exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The last line prints 0, because no trace was recorded. In ordinary Kotlin you would use a labeled return or a function instead (see break, continue and Labels), so treat this as an advanced tool. The trick makes exceptions harder to debug, so use it sparingly and only for exceptions that never indicate a real fault.

Designing good exceptions: a checklist

  1. Decide who the audience is. A message for humans, properties for code.
  2. Say what, not just that. "port must be 1..65535, was 70000" beats "invalid port".
  3. Keep secrets out of messages. Passwords, tokens and card numbers must not appear in exception text, because messages end up in logs.
  4. Make it serializable-friendly and stable. Do not put huge objects or non-serializable resources in properties; they keep memory alive and complicate logging.
  5. Document with KDoc @throws. Since the compiler does not track exceptions, the documentation is the only place where callers learn about them.
  6. Do not catch to log and rethrow at every level. The same error appears ten times in the logs. Handle it once, at the layer that can do something about it, or log at the top.
  7. Do not swallow. An empty catch block turns a clear failure into a mystery. If you truly want to ignore an exception, say why in a comment and keep the catch as narrow as possible.

When Java code calls your Kotlin function, it cannot see which exceptions you may throw unless you add @Throws(OutOfStockException::class). The annotation only matters for Java callers (who then can write catch for a checked exception without a compiler complaint), and it is covered in Java Interoperability.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main benefit of giving a custom exception its own properties, such as shortfall or item?

    The message is for people; properties give the catching code structured information it can act on.
  2. 2. Why pass the original exception as cause when wrapping it in a higher-level one?

    Without the cause, the evidence of what really failed is lost. With it, the stack trace shows the whole chain.
  3. 3. What does a sealed base exception class add?

    All direct subclasses are known at compile time, so the compiler can check that a when expression handles each of them.
  4. 4. A user submits a form with an invalid email address. Which design is usually best?

    Expected business outcomes are best modelled as values; exceptions are for unexpected problems and bugs.
  5. 5. Which is a good practice for catch blocks?

    Handling at the right layer keeps logs clean and behavior clear; empty or repeated catch blocks hide or duplicate problems.

Summary

  • A custom exception extends Exception (or a fitting standard type), has a descriptive name ending in Exception, a useful message and properties that handlers can use.
  • Use one base class per module with a few specific subclasses; make it sealed when the set of failures is closed. Keep hierarchies shallow.
  • Translate low-level exceptions into your domain's at layer boundaries and always keep the original as cause.
  • Kotlin has no checked exceptions; document thrown exceptions with @throws and add @Throws for Java callers.
  • Use exceptions for unexpected problems and bugs, and sealed results (or Result) for outcomes callers expect.
  • Do not swallow exceptions, put secrets in messages, or log-and-rethrow at every level.

Next: Debugging and Printing