Swift example

How to handle errors in Swift

10 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Declare an error type, enum ParseError: Error { case badNumber(String) }, mark the function that can fail throws, and throw a case from it. Call it with try inside do { … } catch { … }; a bare catch gets the error as error. For a readable message, conform to LocalizedError and return the text from errorDescription. try? turns a failure into nil, and try! crashes on one.

Swift has no exceptions in the Java or C++ sense. A function that can fail says so in its signature with throws, every call to it is marked with try, and the error is an ordinary value of a type that conforms to the Error protocol, usually an enum with one case per way things go wrong. The sections below throw and catch errors with pattern matching, give them custom messages, compare try, try? and try!, show the compile error for a missing try, then cover defer, rethrows, typed throws and Result, and end with a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1throws, throw and do/catchRecommended

An enum that conforms to Error is the usual error type: each case is one failure, and associated values carry the details, such as the text that didn't parse. Inside a throws function, throw ends the function and hands the error to the caller. The caller writes try in front of the call and puts it in a do block; the catch clauses are tried in order and can match a case and bind its values, like catch ParseError.badNumber(let text). A catch with no pattern catches everything else and gives you the error as a constant named error. A function that is itself marked throws can skip the do and let errors pass up to its own caller.

throw_catch.swift
enum ParseError: Error {
    case empty
    case badNumber(String)
    case outOfRange(Int, max: Int)
}

// throws: this function can fail with an error instead of returning
func parseAge(_ text: String) throws -> Int {
    guard !text.isEmpty else { throw ParseError.empty }
    guard let age = Int(text) else { throw ParseError.badNumber(text) }
    guard age <= 150 else { throw ParseError.outOfRange(age, max: 150) }
    return age
}

for input in ["42", "", "forty", "200"] {
    do {
        let age = try parseAge(input)
        print("age:", age)
    } catch ParseError.empty {
        print("empty input")
    } catch ParseError.badNumber(let text) {
        print("not a number: \(text)")
    } catch {
        // a bare catch binds the error to the name error
        print("other error: \(error)")
    }
}

// A throwing function can pass errors up to its caller with try
func totalAge(_ inputs: [String]) throws -> Int {
    try inputs.map(parseAge).reduce(0, +)
}

do {
    print("total:", try totalAge(["30", "12"]))
    print("total:", try totalAge(["30", "x"]))
} catch let error as ParseError {
    print("total failed: \(error)")
} catch {
    print("unexpected: \(error)")
}

Output

"42" parses and prints age: 42. The empty string and "forty" each land in the catch that matches their case, and not a number: forty shows the associated value bound by let text. "200" has no clause of its own, so the bare catch prints it as outOfRange(200, max: 150). totalAge has no do at all: the error from "x" passes through it, the second total: line never prints, and catch let error as ParseError receives badNumber("x"). Swift needs the last bare catch because a plain throws function can throw any error type; inside a function, leaving it out is the compile error errors thrown from here are not handled because the enclosing catch is not exhaustive.

2A custom message with LocalizedError

Any type can be an error, so the simplest error with a message is a struct with a message property. But code that shows errors to people usually reads error.localizedDescription, and plain Error types don't fill it in. Conform to LocalizedError instead and implement errorDescription: whatever it returns becomes localizedDescription. For an enum, a switch gives each case its own text. localizedDescription and LocalizedError come from Foundation, so this needs import Foundation.

custom_message.swift
import Foundation

// Error alone: fine for code, but the message is not in the text
struct PlainError: Error {
    let message: String
}

// LocalizedError: errorDescription becomes localizedDescription
struct MessageError: LocalizedError {
    let message: String
    var errorDescription: String? { message }
}

enum ValidationError: LocalizedError {
    case badNumber(String)
    case tooLong(Int, max: Int)

    var errorDescription: String? {
        switch self {
        case .badNumber(let text):
            return "\"\(text)\" is not a number"
        case .tooLong(let length, let max):
            return "Name has \(length) characters, the limit is \(max)"
        }
    }
}

let errors: [Error] = [
    PlainError(message: "Disk is full"),
    MessageError(message: "Disk is full"),
    ValidationError.badNumber("abc"),
    ValidationError.tooLong(42, max: 20),
]
for error in errors {
    print(error.localizedDescription)
}

// print(error) shows the value itself, which is handy in logs
print(errors[0])
print(errors[3])

// Throwing an error with a custom message is one line
func save() throws {
    throw MessageError(message: "Could not save: disk is full")
}

do {
    try save()
} catch {
    print(error.localizedDescription)
}

Output

The plain struct's message never shows up: on Linux here its localizedDescription is the generic The operation could not be completed. (main.PlainError error 1.), and the wording can differ on Apple platforms. The same struct with LocalizedError prints Disk is full, and the enum gives "abc" is not a number and Name has 42 characters, the limit is 20. print(error) ignores all of that and shows the value itself, PlainError(message: "Disk is full") and tooLong(42, max: 20), which is what you want in a log.

3try? and try!

try has two shorter forms for when you don't need the error itself. try? runs the call and gives an optional: the value on success, nil on any error, which then works with ??, if let and compactMap (more in how to unwrap an optional). try! unwraps the result and crashes if the call throws, so it belongs only where an error would be a bug in your own code. On this page a failing try! stops with main/main.swift:9: Fatal error: 'try!' expression unexpectedly raised an error: main.ParseError.badNumber("abc"), followed by a backtrace.

try_optional.swift
enum ParseError: Error {
    case badNumber(String)
}

func parse(_ text: String) throws -> Int {
    guard let number = Int(text) else { throw ParseError.badNumber(text) }
    return number
}

// try? turns the error into nil, so the result is an optional
let good = try? parse("12")
let bad = try? parse("12x")
print(type(of: good), String(describing: good), String(describing: bad))

// Pair it with ?? for a default, or with if let / guard let
let port = (try? parse("http")) ?? 8080
print("port:", port)

if let count = try? parse("3") {
    print("count:", count)
}

// compactMap with try? keeps only the values that parsed
let numbers = ["1", "two", "3", "4x"].compactMap { try? parse($0) }
print(numbers)

// A function that already returns an optional: try? does not nest it
func firstNumber(_ texts: [String]) throws -> Int? {
    try texts.first.map(parse)
}
print(type(of: try? firstNumber(["5"])))

// try! for calls that cannot fail: a crash here would be a bug
let limit = try! parse("100")
print("limit:", limit)

Output

Both results are Optional<Int>: Optional(12) for the good input and nil for "12x". The failed port parse falls back to port: 8080, and compactMap keeps [1, 3] and drops the rest. firstNumber already returns Int?, and try? on it still gives Optional<Int>, not an optional inside an optional. The cost of try? is that the error is gone: you can't tell an empty input from a bad one. When that matters, use do/catch.

4The compile error: “not marked with try”

Swift checks error handling at compile time. Calling a throws function without try is an error, and so is a try outside a do/catch in a function that isn't marked throws itself. The program below never runs.

missing_try.swift
enum ParseError: Error {
    case badNumber(String)
}

func parse(_ text: String) throws -> Int {
    guard let number = Int(text) else { throw ParseError.badNumber(text) }
    return number
}

// A throwing call without try does not compile
let number = parse("12")
print(number)

Output

The compiler stops with error: call can throw but is not marked with 'try' and three notes, which are the three ways out: did you mean to use 'try'?, did you mean to handle error as optional value? (try?) and did you mean to disable error propagation? (try!). Plain try also compiles here, because top-level code may throw, but an error that reaches the top level ends the program like try! does, with Fatal error: Error raised at top level: main.E.bad in a test run. Wrap the call in do/catch instead.

5Cleanup with defer, and rethrows

A defer block runs when the current scope exits, however it exits: a normal return or a thrown error. That makes it the place for cleanup, such as closing a file or releasing a lock, written right next to the code that opened it. rethrows is for functions that take a closure: the function throws only if the closure does, so callers who pass a closure that can't throw don't need try. The standard library uses it for map, filter and friends, which is why try inputs.map(parseAge) worked in section 1.

defer_rethrows.swift
enum JobError: Error {
    case failed(String)
}

// defer runs when the scope exits, whether it returns or throws
func run(_ step: String, fails: Bool) throws {
    print("open \(step)")
    defer { print("close \(step)") }
    if fails {
        throw JobError.failed(step)
    }
    print("done \(step)")
}

for (step, fails) in [("upload", false), ("resize", true)] {
    do {
        try run(step, fails: fails)
    } catch {
        print("caught \(error)")
    }
}

// rethrows: retry throws only when the closure you pass can throw
func retry<T>(_ times: Int, _ body: () throws -> T) rethrows -> T {
    for _ in 1..<times {
        if let value = try? body() {
            return value
        }
    }
    return try body()
}

var attempts = 0
let reply = try retry(3) {
    attempts += 1
    if attempts < 3 { throw JobError.failed("attempt \(attempts)") }
    return "ok after \(attempts) attempts"
}
print(reply)

// A closure that cannot throw: no try needed at the call
let answer = retry(3) { 42 }
print(answer)

Output

For upload, close upload prints after done upload, at the end of the function. For resize the throw skips the rest of the body, yet close resize still prints, before the caller's caught failed("resize"). retry swallows the first two failures with try? and returns ok after 3 attempts; on the last attempt it uses plain try, so a third failure would reach the caller. The second call passes { 42 }, which can't throw, so it is written without try.

6Typed throws and Result

A plain throws function can throw any Error, which is why catches need a final catch-all. Since Swift 6.0 you can name the one type it throws, throws(ParseError); the error in a bare catch then has that type, and throw .badNumber(text) can drop the type name. It compiles here in the Swift 5 language mode too. Result is the other way to pass errors around: an enum with .success(value) and .failure(error) that you can store in an array or hand to a callback, and get() turns it back into a throwing call.

typed_throws.swift
enum ParseError: Error {
    case badNumber(String)
}

// Typed throws: this function can throw only a ParseError
func parse(_ text: String) throws(ParseError) -> Int {
    guard let number = Int(text) else { throw .badNumber(text) }
    return number
}

do {
    print(try parse("12"))
    print(try parse("12x"))
} catch {
    // error is a ParseError here, so the switch needs no default
    switch error {
    case .badNumber(let text):
        print("bad number: \(text)")
    }
}

// Result keeps success or failure as a value you can store
func parseResult(_ text: String) -> Result<Int, ParseError> {
    do {
        return .success(try parse(text))
    } catch {
        return .failure(error)
    }
}

let results = ["7", "x", "21"].map(parseResult)
for result in results {
    switch result {
    case .success(let number):
        print("success: \(number)")
    case .failure(let error):
        print("failure: \(error)")
    }
}

// get() turns a Result back into a throwing call
let total = results.compactMap { try? $0.get() }.reduce(0, +)
print("total:", total)

// Result { ... } wraps any throwing call; the error type is any Error
let wrapped = Result { try parse("5") }
print(type(of: wrapped))

Output

12 prints, then "12x" throws and the catch prints bad number: 12x. The switch on error has no default, because the compiler knows it is a ParseError. parseResult stores each outcome as a value, the loop prints two successes and failure: badNumber("x"), and get() with try? adds the successes up to total: 28. The Result { try … } initializer wraps any throwing call, but its type prints as Result<Int, Error>: the specific error type is lost there, which is why parseResult builds its Result with do/catch. Typed throws suit small, closed sets of errors; most code keeps plain throws.

7Which should you use?

MethodOn an errorYou getBest for
do { try f() } catch { … }Runs a catchThe error valueHandling each kind of failure
try f() in a throws funcPasses it upNothing hereLetting the caller decide
try? f()Returns nilAn optionalDefaults, skipping bad items
try! f()CrashesThe plain valueCalls that cannot fail
throws(MyError)Catch knows the typeA MyErrorSmall, closed sets of errors
Result<T, E>Stores .failureA value to switch onStoring outcomes, callbacks

Frequently asked questions

What is the simplest way to throw an error with a custom message in Swift?

Declare a small struct that conforms to LocalizedError: struct MessageError: LocalizedError { let message: String; var errorDescription: String? { message } }, then throw MessageError(message: "Disk is full"). The catch can read the text with error.localizedDescription. With plain Error instead of LocalizedError, localizedDescription prints a generic "The operation could not be completed." sentence and the message is lost.

What is the difference between try, try? and try!?

try lets the error propagate: you need a do/catch around it or a function marked throws. try? returns an optional and turns any error into nil, so you lose which error it was. try! returns the plain value and crashes with "Fatal error: 'try!' expression unexpectedly raised an error" if the call throws. Use try by default, try? when nil is a fine answer, and try! only when an error would be a bug.

Can I make String conform to Error to throw a message?

You can write extension String: Error {} and then throw "something broke", and you will see it in older answers. Here the compiler warns that it "declares a conformance of imported type 'String' to imported protocol 'Error'" and suggests @retroactive, because the standard library could add the same conformance later. It also makes every string a valid error, and localizedDescription still gives the generic sentence. A one-line struct is clearer.

Why does error.localizedDescription say "The operation could not be completed"?

Because the error type conforms to Error but not to LocalizedError, so Foundation has no message and falls back to a generic sentence with the type name, here (main.PlainError error 1.). Add LocalizedError and implement errorDescription. Without import Foundation there is no localizedDescription at all: the compiler says "value of type 'any Error' has no member 'localizedDescription'".

How do I get the associated value out of a caught error?

Match the case in the catch clause: catch ParseError.badNumber(let text) { … }. In a bare catch, cast first: if case ParseError.badNumber(let text) = error { … }, or catch let error as ParseError and then switch error.

Does Swift have finally?

No. Use defer { … } at the point where you acquire the resource. The block runs when the scope exits, whether by returning normally or by throwing, so it does the job of finally and keeps the cleanup next to the setup.

Run it yourself

Open any of these in the full Swift editor to tweak, run and share.

Swift playground