Swift Error Handling

A portrait painting style image of a pirate holding an iPhone.

by The Captain

May 25, 2023

Swift Error Handling: Try, Catch, and Throw

Simplicity and flexibility are the hallmarks of Swift Error Handling. In Swift, errors can be represented using Error Protocol instance or any type that conforms to this protocol. In this tutorial, you will learn how to handle errors in Swift using Try, Catch, and Throw.

What is Error Handling?

Error handling allows you to respond to unexpected situations while executing your program. Error handling prevents your program from crashing by gracefully handling errors that occur during the execution of your program.

In Swift, errors are represented by instances that conform to the Swift Error Protocol. To handle errors, you use a combination of the keywords try, catch, and throw.

Throwing Errors in Swift

The throw keyword is used to signal the occurrence of an error in a function or method. By default, all functions and methods in Swift are non-throwing. To make a function or method that throws, you need to use the throws keyword in the function or method’s signature.

For example, consider the following code snippet:

enum FileProcessingError: Error {
    case fileReadError
    case fileWriteError

func processFile() throws {
    // throw file processing error
    throw FileProcessingError.fileReadError

In the code above, we defined an enumeration FileProcessingError that conforms to the Error Protocol. We also created a function processFile() that throws a FileProcessingError.fileReadError.

Handling Errors in Swift

The try keyword is used to call a function or method that can throw an error. When a function or method throws an error, the error is caught by a do-catch block.

For example:

do {
   try processFile()
} catch {
   print("An error occurred while processing the file")

In the example, we used try to call processFile() and catch to handle the error. If processFile() does not throw an error, the code inside the do block is executed. Otherwise, the code inside the catch block is executed.

It is possible to catch specific errors using a switch statement:

do {
    try processFile()
} catch FileProcessingError.fileReadError {
    print("An error occurred while reading the file")
} catch FileProcessingError.fileWriteError {
    print("An error occurred while writing to the file")

In the example above, we used a switch statement in the catch block to handle specific errors that can be thrown by processFile().


Swift Error handling is a powerful feature that allows you to handle unexpected situations gracefully without crashing your program. In this tutorial, you learned how to create errors that conform to the Swift Error protocol, throw errors using the throw keyword, and handle errors using the do-catch block in Swift. Proper error handling is critical to building robust and reliable applications.