Panic in Swift

import Foundation

func main() {
    // We'll use fatalError throughout this site to check for
    // unexpected errors. This is the only program on the
    // site designed to cause a fatal error.
    fatalError("a problem")

    // A common use of fatalError is to abort if a function
    // returns an error value that we don't know how to
    // (or want to) handle. Here's an example of
    // causing a fatal error if we get an unexpected error when creating a new file.
    do {
        let _ = try FileManager.default.createFile(atPath: "/tmp/file", contents: nil)
    } catch {
        fatalError(error.localizedDescription)
    }
}

main()

In Swift, we use fatalError() as an equivalent to Go’s panic(). It immediately terminates the program and prints an error message.

Running this program will cause it to terminate, print an error message and stack trace, and exit with a non-zero status.

When the first fatalError in main is triggered, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first fatalError.

$ swift panic.swift
Fatal error: a problem: file panic.swift, line 7
Illegal instruction: 4

Note that unlike some languages which use exceptions for handling of many errors, in Swift it’s idiomatic to use error-indicating return values (via throws and do-catch blocks) wherever possible. The fatalError function should be used sparingly, typically only for debugging or in situations where recovery is impossible.

Swift also provides assert() and precondition() functions which can be used for runtime checks that are disabled in release builds, offering a way to catch programming errors early in development without impacting release performance.