Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 146 ยท Error Handling

Error Handling

Learn Swift error handling: the Error protocol, throws, throw, do-catch with patterns, try, try? and try!, propagation, rethrows and defer.

Things go wrong. A user types "abc" where a number belongs, a file is missing, a value is out of range. A program that ignores this either crashes or quietly produces nonsense. Swift's answer is error handling built into the language: a function declares that it can fail with throws, the failure is a value that conforms to Error, and the compiler forces every caller to deal with it. You cannot forget, because the code does not compile.

In this lesson you will learn the whole cycle: declaring errors, throwing them, catching them with patterns, converting them to optionals with try?, asserting that they cannot happen with try!, and passing them on. You will also see the exact compiler messages when you get it wrong. The next lessons cover Custom Errors, Typed Throws and the Result type.

Describing an error: the Error protocol

Anything can be thrown if its type conforms to the empty protocol Error. By far the most common choice is an enum: one case per kind of failure, with associated values for details. That is the idea from Enumerations put to good use.

A function that can fail is marked with throws after its parameter list. Inside it, throw ends the function immediately with an error. A call to it must be marked with try, and must sit somewhere errors are handled, usually a do block with catch clauses.

Swift Throwing, catching, try? and try!

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 readLine()), it gets the next line from this box.

The loop prints age 42, nothing entered, 'abc' is not a number and other error: outOfRange(200). Walk through the control flow: try parseAge(input) either returns a value, or an error leaves the do block immediately and Swift tests the catch clauses from top to bottom. The first clause that matches wins. Each catch takes a pattern, the same patterns you use in switch (see Pattern Matching), so ParseError.notANumber(let text) both matches the case and binds its payload. The last clause, a bare catch, binds the error to an implicit constant named error.

The last lines show the other two forms of try, which we cover below: try? gave Optional(7) and nil, and try! returned 9.

The compiler will not let you forget

Swift is strict about errors, and the messages are worth reading once so that you recognise them later.

Calling a throwing function without try:

Swift Missing try (fails on purpose)

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 readLine()), it gets the next line from this box.

The error is main.swift:3:9: error: call can throw but is not marked with 'try', followed by three notes that list your options: use try, handle the error as an optional value (try?), or disable error propagation (try!). The word try is also a signal to readers: every point where control might leave early is visible in the source.

Using try where nothing handles the error. A function that is not marked throws must catch everything:

Swift Unhandled error in a normal function (fails on purpose)

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 readLine()), it gets the next line from this box.

You get error: errors thrown from here are not handled. Either mark caller with throws so it passes the problem upward, or wrap the call in do/catch.

A catch that is not exhaustive inside such a function is rejected too:

Swift A catch that does not cover everything (fails on purpose)

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 readLine()), it gets the next line from this box.

The message is errors thrown from here are not handled because the enclosing catch is not exhaustive. Swift cannot prove that only E can be thrown (any Error can, until you use typed throws), so the fix is to add a final bare catch, or to make process itself throws.

Passing errors up: propagation

Most functions should not handle an error themselves. They do not know what the user wants to see. They mark themselves throws and let the caller decide. This is propagation, and it costs one word per call:

Swift Propagating errors with throws and try

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 readLine()), it gets the next line from this box.

The output is 15, then failed: missing("lamp"). The third print in the do block never runs, because the second total call threw. compactMap with try? is a handy idiom: elements that fail become nil and are dropped, so you get [1, 2, 4]. Note that the throwing map family also propagates: try items.map(parse) stops at the first failing element and rethrows.

Cleaning up on the way out

When a function throws, it exits early, so cleanup code placed after the failing line is skipped. Put cleanup in a defer block, which runs on every exit, whether by return or by throw. See defer and Cleanup for more.

Swift defer runs even when the function throws

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 readLine()), it gets the next line from this box.

You see ok 1, cleanup 1, cleanup 2, caught tooBig. Step 2 threw, but its defer still ran, and step 3 was never called.

try? and try!: the shortcuts

Three flavours of try exist, and picking the right one matters.

Form What happens on error Result type
try Error propagates or is caught the normal type
try? Error is swallowed; you get nil optional of the normal type
try! Program crashes the normal type

try? is good when the reason does not matter, such as parsing optional input or using a default: let size = (try? readSize()) ?? 0. It throws away the error, so prefer do/catch when you must log or tell the user what went wrong. Since Swift 5, try? flattens optionals: a throwing function returning Int? gives Int?, not Int??.

try! says "this cannot fail; if it does, crash". It is acceptable for things like a regex literal you wrote yourself, or loading a resource bundled with your program. For input that comes from outside, never use it. Here is what the crash looks like:

Swift try! on a failing call (fails on purpose)

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 readLine()), it gets the next line from this box.

The program prints before, then dies with Fatal error: 'try!' expression unexpectedly raised an error: binary.E.bad and the signal SIGILL. (On a real machine you will see the file name instead of binary.) The line after the call never runs. The same crash, with a different message, happens if you let an error escape from top-level code in main.swift:

Swift An error escaping the top level (fails on purpose)

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 readLine()), it gets the next line from this box.

Top-level code is allowed to use try without do, but if the error is not caught the program ends with Fatal error: Error raised at top level: binary.E.bad. In a real application you handle errors where you can show a message, or exit with a status code.

rethrows

Functions that take a closure as an argument have a special case. map should throw only if your closure throws. The keyword rethrows expresses exactly that:

Swift rethrows

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 readLine()), it gets the next line from this box.

The output is no throw twice, then rethrown a. With a non-throwing closure the caller does not need try at all; with a throwing closure it does. This is how the standard library's map, filter and sort(by:) work. Typed throws, in its own lesson, is the modern generalization.

Errors are values: wrapping and inspecting

An error is just a value, so you can store it, compare cases, cast it with as?, or wrap it in another error to add context while keeping the original cause:

Swift Wrapping an error with context

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 readLine()), it gets the next line from this box.

The result is could not save report.txt: full and then free some space. The wrapper gave the higher layer the name of the document, while as? DiskError retrieved the original cause. Good libraries keep this chain so that a log line can show "what you were doing" and "why it failed". Designing these error types well is the topic of the next lesson.

Pitfalls and good habits

  • Do not throw for normal outcomes. "Not found" in a dictionary lookup is a normal result: return an optional. Throw when the caller needs to know why.
  • Never write an empty catch { }. You are hiding failures. At least log the error.
  • Do not use try! on external input (files, user text, network data).
  • Keep do blocks small so it is clear which call a catch refers to.
  • Async code uses the same rules, with try await (see Introduction to Swift Concurrency).
  • A throws function is slightly more expensive than a plain one, but Swift errors are ordinary return values rather than stack-unwinding exceptions, so the cost is small and predictable. They are not like Java or C# exceptions: nothing happens "behind your back".

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must a type do to be thrown?

    Any type that conforms to Error can be thrown. Enums are the usual choice but structs and classes work too.
  2. 2. What does the compiler say about let x = risky() when risky is declared throws?

    Swift requires every call to a throwing function to be marked with try, try? or try!.
  3. 3. What does try? parseAge("abc") return when parsing fails?

    try? converts the result to an optional and swallows the error: you get nil on failure.
  4. 4. Which catch clause order is correct?

    Clauses are tried top to bottom and the first match wins, so a general catch placed first would hide the specific ones.
  5. 5. What happens when an error escapes top-level code in main.swift?

    An uncaught top-level error terminates the program with a fatal error. Catch it where you can respond to it.

Summary

  • Errors are values of types that conform to Error, usually enums with associated values.
  • Mark failing functions with throws; use throw to fail; mark every call with try.
  • Handle errors with do/catch and patterns; the first matching catch wins, and a bare catch binds error.
  • Functions that do not handle errors must be throws so errors propagate; the compiler enforces exhaustive handling.
  • try? turns failure into nil; try! crashes on failure and is for cases that truly cannot fail.
  • defer runs on both normal and throwing exits; rethrows passes a closure's failures through.
  • Wrap errors with context but keep the underlying cause.
  • Return optionals for ordinary "not found", throw when the caller needs the reason.

Next: Custom Errors