Swift catch error

Error handling is the process of responding to and recovering from error conditions in your program. Swift provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime.

Error handling is the process of responding to and recovering from error conditions in your program. Swift provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime.

Some operations aren’t guaranteed to always complete execution or produce a useful output. Optionals are used to represent the absence of a value, but when an operation fails, it’s often useful to understand what caused the failure, so that your code can respond accordingly.

As an example, consider the task of reading and processing data from a file on disk. There are a number of ways this task can fail, including the file not existing at the specified path, the file not having read permissions, or the file not being encoded in a compatible format. Distinguishing among these different situations allows a program to resolve some errors and to communicate to the user any errors it can’t resolve.

Representing and Throwing Errors¶

In Swift, errors are represented by values of types that conform to the Error protocol. This empty protocol indicates that a type can be used for error handling.

Swift enumerations are particularly well suited to modeling a group of related error conditions, with associated values allowing for additional information about the nature of an error to be communicated. For example, here’s how you might represent the error conditions of operating a vending machine inside a game:

  1. enum VendingMachineError: Error {
  2. case invalidSelection
  3. case insufficientFunds(coinsNeeded: Int)
  4. case outOfStock
  5. }

Throwing an error lets you indicate that something unexpected happened and the normal flow of execution can’t continue. You use a throw statement to throw an error. For example, the following code throws an error to indicate that five additional coins are needed by the vending machine:

  1. throw VendingMachineError.insufficientFunds(coinsNeeded: 5)

Handling Errors¶

When an error is thrown, some surrounding piece of code must be responsible for handling the error—for example, by correcting the problem, trying an alternative approach, or informing the user of the failure.

There are four ways to handle errors in Swift. You can propagate the error from a function to the code that calls that function, handle the error using a docatch statement, handle the error as an optional value, or assert that the error will not occur. Each approach is described in a section below.

When a function throws an error, it changes the flow of your program, so it’s important that you can quickly identify places in your code that can throw errors. To identify these places in your code, write the try keyword—or the try? or try! variation—before a piece of code that calls a function, method, or initializer that can throw an error. These keywords are described in the sections below.

Note

Error handling in Swift resembles exception handling in other languages, with the use of the try, catch and throw keywords. Unlike exception handling in many languages—including Objective-C—error handling in Swift doesn’t involve unwinding the call stack, a process that can be computationally expensive. As such, the performance characteristics of a throw statement are comparable to those of a return statement.

Propagating Errors Using Throwing Functions¶

To indicate that a function, method, or initializer can throw an error, you write the throws keyword in the function’s declaration after its parameters. A function marked with throws is called a throwing function. If the function specifies a return type, you write the throws keyword before the return arrow (->).

  1. func canThrowErrors() throws -> String
  2. func cannotThrowErrors() -> String

A throwing function propagates errors that are thrown inside of it to the scope from which it’s called.

Note

Only throwing functions can propagate errors. Any errors thrown inside a nonthrowing function must be handled inside the function.

In the example below, the VendingMachine class has a vend(itemNamed:) method that throws an appropriate VendingMachineError if the requested item isn’t available, is out of stock, or has a cost that exceeds the current deposited amount:

  1. struct Item {
  2. var price: Int
  3. var count: Int
  4. }
  5. class VendingMachine {
  6. var inventory = [
  7. «Candy Bar»: Item(price: 12, count: 7),
  8. «Chips»: Item(price: 10, count: 4),
  9. «Pretzels»: Item(price: 7, count: 11)
  10. ]
  11. var coinsDeposited = 0
  12. func vend(itemNamed name: String) throws {
  13. guard let item = inventory[name] else {
  14. throw VendingMachineError.invalidSelection
  15. }
  16. guard item.count > 0 else {
  17. throw VendingMachineError.outOfStock
  18. }
  19. guard item.price <= coinsDeposited else {
  20. throw VendingMachineError.insufficientFunds(coinsNeeded: item.pricecoinsDeposited)
  21. }
  22. coinsDeposited -= item.price
  23. var newItem = item
  24. newItem.count -= 1
  25. inventory[name] = newItem
  26. print(«Dispensing (name)«)
  27. }
  28. }

The implementation of the vend(itemNamed:) method uses guard statements to exit the method early and throw appropriate errors if any of the requirements for purchasing a snack aren’t met. Because a throw statement immediately transfers program control, an item will be vended only if all of these requirements are met.

Because the vend(itemNamed:) method propagates any errors it throws, any code that calls this method must either handle the errors—using a docatch statement, try?, or try!—or continue to propagate them. For example, the buyFavoriteSnack(person:vendingMachine:) in the example below is also a throwing function, and any errors that the vend(itemNamed:) method throws will propagate up to the point where the buyFavoriteSnack(person:vendingMachine:) function is called.

  1. let favoriteSnacks = [
  2. «Alice»: «Chips»,
  3. «Bob»: «Licorice»,
  4. «Eve»: «Pretzels»,
  5. ]
  6. func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
  7. let snackName = favoriteSnacks[person] ?? «Candy Bar»
  8. try vendingMachine.vend(itemNamed: snackName)
  9. }

In this example, the buyFavoriteSnack(person: vendingMachine:) function looks up a given person’s favorite snack and tries to buy it for them by calling the vend(itemNamed:) method. Because the vend(itemNamed:) method can throw an error, it’s called with the try keyword in front of it.

Throwing initializers can propagate errors in the same way as throwing functions. For example, the initializer for the PurchasedSnack structure in the listing below calls a throwing function as part of the initialization process, and it handles any errors that it encounters by propagating them to its caller.

  1. struct PurchasedSnack {
  2. let name: String
  3. init(name: String, vendingMachine: VendingMachine) throws {
  4. try vendingMachine.vend(itemNamed: name)
  5. self.name = name
  6. }
  7. }

Handling Errors Using Do-Catch¶

You use a docatch statement to handle errors by running a block of code. If an error is thrown by the code in the do clause, it’s matched against the catch clauses to determine which one of them can handle the error.

Here is the general form of a docatch statement:

  1. do {
  2. try expression
  3. statements
  4. } catch pattern 1 {
  5. statements
  6. } catch pattern 2 where condition {
  7. statements
  8. } catch pattern 3, pattern 4 where condition {
  9. statements
  10. } catch {
  11. statements
  12. }

You write a pattern after catch to indicate what errors that clause can handle. If a catch clause doesn’t have a pattern, the clause matches any error and binds the error to a local constant named error. For more information about pattern matching, see Patterns.

For example, the following code matches against all three cases of the VendingMachineError enumeration.

  1. var vendingMachine = VendingMachine()
  2. vendingMachine.coinsDeposited = 8
  3. do {
  4. try buyFavoriteSnack(person: «Alice», vendingMachine: vendingMachine)
  5. print(«Success! Yum.»)
  6. } catch VendingMachineError.invalidSelection {
  7. print(«Invalid Selection.»)
  8. } catch VendingMachineError.outOfStock {
  9. print(«Out of Stock.»)
  10. } catch VendingMachineError.insufficientFunds(let coinsNeeded) {
  11. print(«Insufficient funds. Please insert an additional (coinsNeeded) coins.»)
  12. } catch {
  13. print(«Unexpected error: (error))
  14. }
  15. // Prints «Insufficient funds. Please insert an additional 2 coins.»

In the above example, the buyFavoriteSnack(person:vendingMachine:) function is called in a try expression, because it can throw an error. If an error is thrown, execution immediately transfers to the catch clauses, which decide whether to allow propagation to continue. If no pattern is matched, the error gets caught by the final catch clause and is bound to a local error constant. If no error is thrown, the remaining statements in the do statement are executed.

The catch clauses don’t have to handle every possible error that the code in the do clause can throw. If none of the catch clauses handle the error, the error propagates to the surrounding scope. However, the propagated error must be handled by some surrounding scope. In a nonthrowing function, an enclosing docatch statement must handle the error. In a throwing function, either an enclosing docatch statement or the caller must handle the error. If the error propagates to the top-level scope without being handled, you’ll get a runtime error.

For example, the above example can be written so any error that isn’t a VendingMachineError is instead caught by the calling function:

  1. func nourish(with item: String) throws {
  2. do {
  3. try vendingMachine.vend(itemNamed: item)
  4. } catch is VendingMachineError {
  5. print(«Couldn’t buy that from the vending machine.»)
  6. }
  7. }
  8. do {
  9. try nourish(with: «Beet-Flavored Chips»)
  10. } catch {
  11. print(«Unexpected non-vending-machine-related error: (error)«)
  12. }
  13. // Prints «Couldn’t buy that from the vending machine.»

In the nourish(with:) function, if vend(itemNamed:) throws an error that’s one of the cases of the VendingMachineError enumeration, nourish(with:) handles the error by printing a message. Otherwise, nourish(with:) propagates the error to its call site. The error is then caught by the general catch clause.

Another way to catch several related errors is to list them after catch, separated by commas. For example:

  1. func eat(item: String) throws {
  2. do {
  3. try vendingMachine.vend(itemNamed: item)
  4. } catch VendingMachineError.invalidSelection, VendingMachineError.insufficientFunds, VendingMachineError.outOfStock {
  5. print(«Invalid selection, out of stock, or not enough money.»)
  6. }
  7. }

The eat(item:) function lists the vending machine errors to catch, and its error text corresponds to the items in that list. If any of the three listed errors are thrown, this catch clause handles them by printing a message. Any other errors are propagated to the surrounding scope, including any vending-machine errors that might be added later.

Converting Errors to Optional Values¶

You use try? to handle an error by converting it to an optional value. If an error is thrown while evaluating the try? expression, the value of the expression is nil. For example, in the following code x and y have the same value and behavior:

  1. func someThrowingFunction() throws -> Int {
  2. // …
  3. }
  4. let x = try? someThrowingFunction()
  5. let y: Int?
  6. do {
  7. y = try someThrowingFunction()
  8. } catch {
  9. y = nil
  10. }

If someThrowingFunction() throws an error, the value of x and y is nil. Otherwise, the value of x and y is the value that the function returned. Note that x and y are an optional of whatever type someThrowingFunction() returns. Here the function returns an integer, so x and y are optional integers.

Using try? lets you write concise error handling code when you want to handle all errors in the same way. For example, the following code uses several approaches to fetch data, or returns nil if all of the approaches fail.

  1. func fetchData() -> Data? {
  2. if let data = try? fetchDataFromDisk() { return data }
  3. if let data = try? fetchDataFromServer() { return data }
  4. return nil
  5. }

Disabling Error Propagation¶

Sometimes you know a throwing function or method won’t, in fact, throw an error at runtime. On those occasions, you can write try! before the expression to disable error propagation and wrap the call in a runtime assertion that no error will be thrown. If an error actually is thrown, you’ll get a runtime error.

For example, the following code uses a loadImage(atPath:) function, which loads the image resource at a given path or throws an error if the image can’t be loaded. In this case, because the image is shipped with the application, no error will be thrown at runtime, so it’s appropriate to disable error propagation.

  1. let photo = try! loadImage(atPath: «./Resources/John Appleseed.jpg»)

Specifying Cleanup Actions¶

You use a defer statement to execute a set of statements just before code execution leaves the current block of code. This statement lets you do any necessary cleanup that should be performed regardless of how execution leaves the current block of code—whether it leaves because an error was thrown or because of a statement such as return or break. For example, you can use a defer statement to ensure that file descriptors are closed and manually allocated memory is freed.

A defer statement defers execution until the current scope is exited. This statement consists of the defer keyword and the statements to be executed later. The deferred statements may not contain any code that would transfer control out of the statements, such as a break or a return statement, or by throwing an error. Deferred actions are executed in the reverse of the order that they’re written in your source code. That is, the code in the first defer statement executes last, the code in the second defer statement executes second to last, and so on. The last defer statement in source code order executes first.

  1. func processFile(filename: String) throws {
  2. if exists(filename) {
  3. let file = open(filename)
  4. defer {
  5. close(file)
  6. }
  7. while let line = try file.readline() {
  8. // Work with the file.
  9. }
  10. // close(file) is called here, at the end of the scope.
  11. }
  12. }

The above example uses a defer statement to ensure that the open(_:) function has a corresponding call to close(_:).

Note

You can use a defer statement even when no error handling code is involved.

Обработка ошибок

Обработка ошибок — это процесс реагирования на возникновение ошибок и восстановление после появления ошибок в программе. Swift предоставляет первоклассную поддержку при генерации, вылавливании и переносе ошибок, устранении ошибок во время выполнения программы.

Некоторые операции не всегда гарантируют полное выполнение или конечный результат. Опционалы используются для обозначения отсутствия значения, но когда случается сбой, важно понять, что вызвало сбой, для того, чтобы соответствующим образом изменить код.

В качестве примера, рассмотрим задачу считывания и обработки данных из файла на диске. Задача может провалиться по нескольким причинам, в том числе: файл не существует по указанному пути, или файл не имеет разрешение на чтение, или файл не закодирован в необходимом формате. Отличительные особенности этих различных ситуаций позволяют программе решать некоторые ошибки самостоятельно и сообщать пользователю какие ошибки она не может решить сама.

Отображение и генерация ошибок

В Swift ошибки отображаются значениями типов, которые соответствуют протоколу Error. Этот пустой протокол является индикатором того, что это перечисление может быть использовано для обработки ошибок.

Перечисления в Swift особенно хорошо подходят для группировки схожих между собой условий возникновения ошибок и соответствующих им значений, что позволяет получить дополнительную информацию о природе самой ошибки. Например, вот как отображаются условия ошибки работы торгового автомата внутри игры:

enum VendingMachineError: Error {
    case invalidSelection
    case insufficientFunds(coinsNeeded: Int)
    case outOfStock
}

Генерация ошибки позволяет указать, что произошло что-то неожиданное и обычное выполнение программы не может продолжаться. Для того чтобы «сгенерировать» ошибку, вы используете инструкцию throw. Например, следующий код генерирует ошибку, указывая, что пять дополнительных монет нужны торговому автомату:

throw VendingMachineError.insufficientFunds(coinsNeeded: 5)

Обработка ошибок

Когда генерируется ошибка, то фрагмент кода, окружающий ошибку, должен быть ответственным за ее обработку: например, он должен исправить ее, или испробовать альтернативный подход, или просто информировать пользователя о неудачном исполнении кода.

В Swift существует четыре способа обработки ошибок. Вы можете передать (propagate) ошибку из функции в код, который вызывает саму эту функцию, обработать ошибку, используя инструкцию do-catch, обработать ошибку, как значение опционала, или можно поставить утверждение, что ошибка в данном случае исключена. Каждый вариант будет рассмотрен далее.

Когда функция генерирует ошибку, последовательность выполнения вашей программы меняется, поэтому важно сразу обнаружить место в коде, которое может генерировать ошибки. Для того, чтобы выяснить где именно это происходит, напишите ключевое слово try — или варианты try? или try!— до куска кода, вызывающего функцию, метод или инициализатор, который может генерировать ошибку. Эти ключевые слова описываются в следующем параграфе.

Заметка

Обработка ошибок в Swift напоминает обработку исключений (exceptions) в других языках, с использованием ключевых слов try, catch и throw. В отличие от обработки исключений во многих языках, в том числе и в Objective-C- обработка ошибок в Swift не включает разворачивание стека вызовов, то есть процесса, который может быть дорогим в вычислительном отношении. Таким образом, производительные характеристики инструкции throw сопоставимы с характеристиками оператора return.

Передача ошибки с помощью генерирующей функции

Чтобы указать, что функция, метод или инициализатор могут генерировать ошибку, вам нужно написать ключевое слово throws в реализации функции после ее параметров. Функция, отмеченная throws называется генерирующей функцией. Если у функции установлен возвращаемый тип, то вы пишете ключевое слово throws перед стрелкой возврата (->).

func canThrowErrors() throws -> String
func cannotThrowErrors() -> String

Генерирующая функция передает ошибки, которые возникают внутри нее в область вызова этой функции.

Заметка

Только генерирующая ошибку функция может передавать ошибки. Любые ошибки, сгенерированные внутри non-throwing функции, должны быть обработаны внутри самой функции.

В приведенном ниже примере VendingMachine класс имеет vend(itemNamed: ) метод, который генерирует соответствующую VendingMachineError, если запрошенный элемент недоступен, его нет в наличии, или имеет стоимость, превышающую текущий депозит:

struct Item {
    var price: Int
    var count: Int
}
 
class VendingMachine {
    var inventory = [
        "Candy Bar": Item(price: 12, count: 7),
        "Chips": Item(price: 10, count: 4),
        "Pretzels": Item(price: 7, count: 11)
    ]
    var coinsDeposited = 0
    
    func vend(itemNamed name: String) throws {
        guard let item = inventory[name] else {
            throw VendingMachineError.invalidSelection
        }
        
        guard item.count > 0 else {
            throw VendingMachineError.outOfStock
        }
        
        guard item.price <= coinsDeposited else {
            throw VendingMachineError.insufficientFunds(coinsNeeded: item.price - coinsDeposited)
        }
        
        coinsDeposited -= item.price
        
        var newItem = item
        newItem.count -= 1
        inventory[name] = newItem
        
        print("Dispensing (name)")
    }
}

Реализация vend(itemNamed: ) метода использует оператор guard для раннего выхода из метода и генерации соответствующих ошибок, если какое-либо требование для приобретения закуски не будет выполнено. Потому что инструкция throw мгновенно изменяет управление программой, и выбранная позиция будет куплена, только если все эти требования будут выполнены.

Поскольку vend(itemNamed: ) метод передает все ошибки, которые он генерирует, вызывающему его коду, то они должны быть обработаны напрямую, используя оператор do-catch, try? или try!, или должны быть переданы дальше. Например, buyFavoriteSnack(person:vendingMachine: ) в примере ниже — это тоже генерирующая функция, и любые ошибки, которые генерирует метод vend(itemNamed: ), будут переноситься до точки, где будет вызываться функция buyFavoriteSnack(person:vendingMachine: ).

let favoriteSnacks = [
    "Alice": "Chips",
    "Bob": "Licorice",
    "Eve": "Pretzels"
]
func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
    let snackName = favoriteSnacks[person] ?? "Candy Bar"
    try vendingMachine.vend(itemNamed: snackName)
}

В этом примере, функция buyFavoriteSnack(person:vendingMachine: ) подбирает любимые закуски данного человека и пытается их купить, вызывая vend(itemNamed: ) метод. Поскольку метод vend(itemNamed: ) может сгенерировать ошибку, он вызывается с ключевым словом try перед ним.

Генерирующие ошибку инициализаторы могут распространять ошибки таким же образом, как генерирующие ошибку функции. Например, инициализатор структуры PurchasedSnack в списке ниже вызывает генерирующую ошибку функции как часть процесса инициализации, и он обрабатывает любые ошибки, с которыми сталкивается, путем распространения их до вызывающего его объекта.

struct PurchasedSnack {
    let name: String
    init(name: String, vendingMachine: VendingMachine) throws {
        try vendingMachine.vend(itemNamed: name)
        self.name = name
    }
}

Обработка ошибок с использованием do-catch

Используйте инструкцию do-catch для обработки ошибок, запуская блок кода. Если выдается ошибка в коде условия do, она соотносится с условием catch для определения того, кто именно сможет обработать ошибку.

Вот общий вид условия do-catch:

do {
    try выражение
    выражение
} catch шаблон 1 {
    выражение
} catch шаблон 2  where условие {
    выражение
} catch шаблон 3, шаблон 4 where условие {
    выражение
} catch {
    выражение
}

Вы пишете шаблон после ключевого слова catch, чтобы указать какие ошибки могут обрабатываться данным пунктом этого обработчика. Если условие catch не имеет своего шаблона, то оно подходит под любые ошибки и связывает ошибки к локальной константе error. Более подробно о соответствии шаблону см. Шаблоны.

Например, следующий код обрабатывает все три случая в перечислении VendingMachineError, но все другие ошибки должны быть обработаны окружающей областью:

var vendingMachine = VendingMachine()
vendingMachine.coinsDeposited = 8
do {
    try buyFavoriteSnack(person: "Alice", vendingMachine: vendingMachine)
} catch VendingMachineError.invalidSelection {
    print("Ошибка выбора.")
} catch VendingMachineError.outOfStock {
    print("Нет в наличии.")
} catch VendingMachineError.insufficientFunds(let coinsNeeded) {
    print("Недостаточно средств. Пожалуйста вставьте еще (coinsNeeded) монетки.")
} catch {
    print("Неожиданная ошибка: (error).")
}
// Выведет "Недостаточно средств. Пожалуйста вставьте еще 2 монетки.

В приведенном выше примере, buyFavoriteSnack(person:vendingMachine: ) функция вызывается в выражении try, потому что она может сгенерировать ошибку. Если генерируется ошибка, выполнение немедленно переносится в условия catch, которые принимают решение о продолжении передачи ошибки. Если ошибка не генерируется, остальные операторы do выполняются.

В условии catch не нужно обрабатывать все возможные ошибки, которые может вызвать код в условии do. Если ни одно из условий catch не обрабатывает ошибку, ошибка распространяется на окружающую область. Однако распространяемая ошибка должна обрабатываться некоторой внешней областью. В функции nonthrowing условие включения do-catch должно обрабатывать ошибку. В функции throwing либо включающая условие do-catch, либо вызывающая сторона должна обрабатывать ошибку. Если ошибка распространяется на область верхнего уровня без обработки, вы получите ошибку исполнения.

Например, приведенный ниже пример можно записать так, чтобы любая ошибка, которая не является VendingMachineError, вместо этого захватывалась вызывающей функцией:

func nourish(with item: String) throws {
    do {
        try vendingMachine.vend(itemNamed: item)
    } catch is VendingMachineError {
        print("Некорректный вывод, нет в наличии или недостаточно денег.")
    }
}

do {
    try nourish(with: "Beet-Flavored Chips")
} catch {
    print("Unexpected non-vending-machine-related error: (error)")
}
// Выведет "Некорректный вывод, нет в наличии или недостаточно денег."

В nourish(with: ), если vend(itemNamed : ) выдает ошибку, которая является одним из кейсов перечисления VendingMachineError, nourish(with: ) обрабатывает ошибку, печатая сообщение. В противном случае, nourish(with: ) распространяет ошибку на свое место вызова. Ошибка затем попадает в общее условие catch.

Преобразование ошибок в опциональные значения

Вы можете использовать try? для обработки ошибки, преобразовав ее в опциональное значение. Если ошибка генерируется при условии try?, то значение выражения вычисляется как nil. Например, в следующем коде x и y имеют одинаковые значения и поведение:

func someThrowingFunction() throws -> Int {
    // ...
}
 
let x = try? someThrowingFunction()
 
let y: Int?
do {
    y = try someThrowingFunction()
} catch {
    y = nil
}

Если someThrowingFunction() генерирует ошибку, значение x и y равно nil. В противном случае значение x и y — это возвращаемое значение функции. Обратите внимание, что x и y являются опциональными, независимо от того какой тип возвращает функция someThrowingFunction().

Использование try? позволяет написать краткий код обработки ошибок, если вы хотите обрабатывать все ошибки таким же образом. Например, следующий код использует несколько попыток для извлечения данных или возвращает nil, если попытки неудачные.

func fetchData() -> Data? {
    if let data = try? fetchDataFromDisk() { return data }
    if let data = try? fetchDataFromServer() { return data }
    return nil
}

Запрет на передачу ошибок

Иногда вы знаете, что функции throw или методы не сгенерируют ошибку во время исполнения. В этих случаях, вы можете написать try! перед выражением для запрета передачи ошибки и завернуть вызов в утверждение того, что ошибка точно не будет сгенерирована. Если ошибка на самом деле сгенерирована, вы получите сообщение об ошибке исполнения.

Например, следующий код использует loadImage(atPath: ) функцию, которая загружает ресурс изображения по заданному пути или генерирует ошибку, если изображение не может быть загружено. В этом случае, поскольку изображение идет вместе с приложением, сообщение об ошибке не будет сгенерировано во время выполнения, поэтому целесообразно отключить передачу ошибки.

let photo = try! loadImage(atPath: "./Resources/John Appleseed.jpg")

Установка действий по очистке (Cleanup)

Вы используете оператор defer для выполнения набора инструкций перед тем как исполнение кода оставит текущий блок. Это позволяет сделать любую необходимую очистку, которая должна быть выполнена, независимо от того, как именно это произойдет — либо он покинет из-за сгенерированной ошибки или из-за оператора, такого как break или return. Например, вы можете использовать defer, чтобы удостовериться, что файл дескрипторов закрыт и выделенная память вручную освобождена.

Оператор defer откладывает выполнение, пока не происходит выход из текущей области. Этот оператор состоит из ключевого слова defer и выражений, которые должны быть выполнены позже. Отложенные выражения могут не содержать кода, изменяющего контроль исполнения изнутри наружу, при помощи таких операторов как break или return, или просто генерирующего ошибку. Отложенные действия выполняются в обратном порядке, как они указаны, то есть, код в первом операторе defer выполняется после кода второго, и так далее.

func processFile(filename: String) throws {
    if exists(filename) {
        let file = open(filename)
        defer {
            close(file)
        }
        while let line = try file.readline() {
            // работаем с файлом.
        }
        // close(file) вызывается здесь, в конце зоны видимости.
    }
}

Приведенный выше пример использует оператор defer, чтобы удостовериться, что функция open(_: ) имеет соответствующий вызов и для close(_: ).

Заметка

Вы можете использовать оператор defer, даже если не используете кода обработки ошибок.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Мы используем обработку ошибок с помощью do-try-catch для реагирования на исправимые ошибки. Это дает нам больший контроль над различными ошибочными сценариями, которые могут возникнуть в нашем коде, например, при вводе неправильного имени пользователя или пароля.

Зачем нужно отслеживать ошибки?

В приложении некоторые ошибки могут быть результатом ошибок программиста. Когда ваше приложение вылетает с сообщением «Index out of bounds», вы, вероятно, где-то допустили ошибку. И точно так же, когда вы принудительно извлекаете опциональное значение, которое имеет значение nil, ваше приложение падает.

В практической разработке iOS некоторые ошибки являются частью работы приложения, например, сообщение «Недостаточно средств» при попытке оплаты с помощью карты.

Ошибки такого рода исправимы. Их можно обработать и отреагировать соответствующим образом. К примеру:

  • При попытке снять деньги в банкомате отображается «Неверный PIN-код».
  • Ваш автомобиль показывает индикатор низкого уровня топлива при попытке запустить двигатель.
  • Попытка аутентификации для API возвращает «Неверное имя пользователя / пароль».

Вы можете работать с этими ошибками, отобразив сообщение с предупреждением или сделав что-то еще. Например, ваша карта блокируется после 3 неудачных попыток. Ваш автомобиль может указать вам ближайшую заправку, когда у вас кончается бензин. Вы можете попробовать ввести другое имя пользователя и пароль.

Swift поддерживает обработку ошибок с помощью блока кода do-try-catch.

Выбрасывание ошибок

Когда в вашем коде возникает сценарий, который может привести к ошибке, вы можете выбросить ошибку:

if fuel < 1000 {
    throw RocketError.insufficientFuel
}

В приведенном выше коде ключевое слово throw используется для выдачи ошибки типа RocketError.insufficientFuel, когда переменная fuel меньше, чем 1000.

Представьте, что мы пытаемся запустить ракету:

func igniteRockets(fuel: Int, astronauts: Int) throws {
    if fuel < 1000 {
        throw RocketError.insufficientFuel
    }
    else if astronauts < 3 {
        throw RocketError.insufficientAstronauts(needed: 3)
    }
 
    // Запуск ракеты
    print("3... 2... 1... Старт!")
}

Функция igniteRockets(fuel:astronauts:) будет запускать ракеты, только если значение fuel больше или равно 1000 и если на борту есть как минимум 3 астронавта.

Функция igniteRockets(…) также помечается ключевым словом throws. Это ключевое слово указывает, что ошибки должны быть обработаны.

В приведенном выше коде мы используем тип ошибки RocketError:

enum RocketError: Error {
    case insufficientFuel
    case insufficientAstronauts(needed: Int)
    case unknownError
}

Данное перечисление определяет три типа ошибок: .insufficientFuel, insufficientAstronauts(needed) и .unknownError. Определение ваших собственных типов ошибок полезно, потому что это поможет четко понять, что эти ошибки означают в вашем коде.

Возьмем, например, ошибку insufficientAstronauts(needed:). Когда выдается эта ошибка, вы можете использовать аргумент needed:, который указывает, сколько астронавтов необходимо для успешного запуска ракеты.

Ключевое слово throw имеет тот же эффект, что и ключевое слово return. Когда выполняется throw, выполнение функции останавливается, и выброшенная ошибка передается вызывающей функции.

Теперь мы можем использовать обработку ошибок, чтобы соответствующим образом реагировать на сценарии ошибок. Обработка ошибок в Swift осуществляется с помощью блока кода do-try-catch:

do {
    try igniteRockets(fuel: 5000, astronauts: 1)    
} catch {
    print(error)
}

Обработка ошибок имеет три аспекта:

  • К функции, которая может вызвать ошибку, добавляется ключевое слово try.
  • Блок кода, который включает ключевое слово try, обернут в do { … }.
  • Один или несколько блоков catch { … } могут быть присоединены к do { … } для обработки отдельных случаев ошибок.

Если функция выдает ошибку, вызывается блок catch. В данном случае это выводит ошибку на консоль.

Вы также можете реагировать на ошибки в индивидуальном порядке:

do {
    try igniteRockets(fuel: 5000, astronauts: 1)    
} catch RocketError.insufficientFuel {
    print("Ракете нужно больше топлива!")
} catch RocketError.insufficientAstronauts(let needed) {
    print("Нужно как минимум (needed) астронавта...")
}

Вышеуказанные блоки catch вызываются на основании отдельных перечислений RocketError. Вы можете напрямую получить доступ к связанным значениям перечислений, таких как needed. Также вы можете использовать выражения с шаблоном where чтобы получить больший контроль над ошибочным сценарием.

enum RocketError: Error {
    case insufficientFuel
    case insufficientAstronauts(needed: Int)
    case unknownError
}
 
func igniteRockets(fuel: Int, astronauts: Int) throws {
    if fuel < 1000 {
        throw RocketError.insufficientFuel
    }
    else if astronauts < 3 {
        throw RocketError.insufficientAstronauts(needed: 3)
    }
 
    // Ignite rockets
    print("3... 2... 1... Полет!")
}
 
do {
    try igniteRockets(fuel: 5000, astronauts: 1)
} catch {
    print(error)
}

Преобразование ошибок в опционалы с помощью try?

Целью обработки ошибок является явное определение того, что происходит при возникновении ошибки. Это позволяет нам реагировать определенным образом на ошибки.

В некоторых случаях нас не волнует сама ошибка. Нам просто нужно получить значение из функции. И если возникает ошибка, мы можем возвратить nil. Эта возможность доступна с помощью ключевого слова try? Когда вы используете try?, вам не нужно использовать полный блок кода do-try-catch.

let result = try? calculateValue(for: 42)

Представьте, что функция может выбрасывать ошибки, если ее параметр недействителен. Вместо обработки ошибки мы конвертируем возвращаемое значение в опциональное.

Возможны два сценария:

  • Функция не выдает ошибку и возвращает значение, которое присваивается константе result.
  • Функция выдает ошибку и не возвращает значение. Это означает, что константе result присваивается nil.

Обработка ошибок с помощью try? означает, что вы можете воспользоваться синтаксисом, специфичным для опционалов, таких как объединение по nil и опциональное связывание:

if let result = try? calculateValue(for: 99) {
    // 
}
 
let result = try? calculateValue(for: 123) ?? 101

Отключение обработки ошибок с помощью try!

Вы можете полностью отключить обработку ошибок с помощью try!. Ключевое слово try! используется для принудиального извлечения опционального значения.

В отличие от того try?, который возвращает опциональное значение, синтаксис try! приведет к сбою вашего кода в случае возникновения ошибки. Есть два различных сценария, в которых использование try! может быть полезно:

  • Используйте try!, когда вы на 100% уверенны, что ошибка не возникнет.
  • Используйте, try!, когда невозможно продолжить выполнение кода.

Представьте, что вы пишите приложение, в которое встроен файл базы данных. Функция загрузки базы данных выдает ошибку, когда база данных повреждена. Вы можете использовать try! для загрузки базы данных в память, потому что, если база данных повреждена, приложение все равно не сможет быть использовано.

Try catch in Swift combined with throwing errors make it possible to nicely handle any failures in your code. A method can be defined as throwing which basically means that if anything goes wrong, it can throw an error. To catch this error, we need to implement a so-called do-catch statement.

It’s not always required to use a do-catch statement with throwing method. Let’s go over all the cases and cover them in more detail.

Learn about the 3-step process to transition your iOS development to Apple M1 silicon Macs — with insights from Reddit’s successful M1 transition, FAQs, and helpful M1 transition tips.

Creating a throwing method using the throws keyword

Creating a throwing method is as easy as adding the throws keyword to a method just before the return statement. In this example, we use a method to update the name for a user of a specific user identifier.

func update(name: String, forUserIdentifier userIdentifier: String) {
    // This method is not throwing any errors
}

func update(name: String, forUserIdentifier userIdentifier: String) throws {
    // The throws keyword makes that this method cán throw an error
}

When calling a throwing method you might get the following error:

Call can throw but is not marked with ‘try’

This means that you have to use the try keyword before a piece of code that can throw an error.

try update(name: "Antoine van der Lee", forUserIdentifier: "AEDKM1323")

Throwing initializer in Swift

A great thing is that you can also create a throwing initializer. This especially comes in handy when you want to validate properties for initializing a certain object. For example, you might want to validate a username before creating a User object.

struct User {
    enum ValidationError: Error {
        case emptyName
        case nameToShort(nameLength: Int)
    }

    let name: String

    init(name: String) throws {
        guard !name.isEmpty else {
            throw ValidationError.emptyName
        }
        guard name.count > 2 else {
            throw ValidationError.nameToShort(nameLength: name.count)
        }

        self.name = name
    }
}

let user = try User(name: "Antoine van der Lee")

Swift Try Catch: Handling Errors in Swift with a do-catch statement

To catch a thrown error in Swift we need to use the do-catch statement. The following example uses the earlier defined User instance.

do {
    let user = try User(name: "")
    print("Created user with name (user.name)")
} catch {
    print("User creation failed with error: (error)")
}

// Prints: User creation failed with error: emptyName

The emptyName error is thrown as the provided username is empty. The result is that the catch block is called. As you can see we can use a local error property to print out the caught error. The catch block is only called when an error occurs.

Catching a specific type of error

As we can’t specify the error type which will be thrown by a method we have to take into account that different kinds of error types can be thrown. Therefore, you want to catch and handle specific error types in a separate catch statement.

In the following example, we have implemented the name update method. This method can now throw both a user validation error and a database error thrown from the fetchUser method.

func fetchUser(for identifier: String) throws -> User {
    // Fetches the user from the database
}

func update(name: String, forUserIdentifier userIdentifier: String) throws {
    guard !name.isEmpty else {
        throw User.ValidationError.emptyName
    }
    var user = try fetchUser(for: userIdentifier)
    user.update(name)
    user.save()
}

It would be nice to catch the errors in separated blocks to display a different alert if only the name is invalid. There are several ways of doing this:

do {
    try update(name: "Antoine van der Lee", forUserIdentifier: "AEDKM1323")
} catch User.ValidationError.emptyName {
    // Called only when the `User.ValidationError.emptyName` error is thrown
} catch User.ValidationError.nameToShort(let nameLength) where nameLength == 1 {
    // Only when the `nameToShort` error is thrown for an input of 1 character
} catch is User.ValidationError {
    // All `User.ValidationError` types except for the earlier catch `emptyName` error.
} catch {
    // All other errors
}

There are a few things to point out here:

  • The order of catching is important. In this example, we first catch emptyName specific, all other User.ValidationError after that. If we would swap these two, the specific emptyName catch would never be called.
  • where can be used to filter down on error values. In this example, we only like to catch name inputs with a length of 1 character specifically. If you’re not familiar with the “where” keyword, you can check out my blog post Where usage in Swift.
  • Using the is keyword we can catch errors of a specific type.
  • The generic catch closure in the end catches all other errors.

There’s also scenarios in which you’d like to catch two or more specific error types. In this case, you can use lists in your catch statements:

do {
    try update(name: "Antoine van der Lee", forUserIdentifier: "AEDKM1323")
} catch User.ValidationError.emptyName, User.ValidationError.nameToShort {
    // Only called for `emptyName` and `nameToShort`
} catch {
    // All other errors
}

Note here that we took away the nameToShort paramater. This is something you can always do when working with enums if you’re not interested in the associated value.

Using try? with a throwing method

If you’re not interested in catching any thrown errors you can also decide to use try?. The question mark behind the try keyword basically tells that we’re not interested in the possibly thrown error.

let user = try? User(name: "")
print(user?.name) // Prints "nil" if an error occurred upon init.

The value will either be an optional User instance or nil and the thrown error is completely ignored.

Using try! with a throwing method

If you want your app to fail instantly you can use try! with the throwing method. This will basically fail your app just like a fatal error statement.

let user = try! User(name: "")
print(user.name)

This will end up with the following error as the name input is empty:

Fatal error: ‘try!’ expression unexpectedly raised an error: User.ValidationError.emptyName

Learn about the 3-step process to transition your iOS development to Apple M1 silicon Macs — with insights from Reddit’s successful M1 transition, FAQs, and helpful M1 transition tips.

Conclusion

Error handling in Swift is great. It allows you to write readable code while also handling the non-happy flow. By being able to catch specific error types or using the where keyword we have the flexibility to handle specific scenarios if needed. Be a good citizen and make your methods throw whenever it can fail!

If you like to improve your Swift knowledge, even more, check out the Swift category page. Feel free to contact me or tweet to me on Twitter if you have any additional tips or feedback.

Thanks!

It is tempting to just catch all a throwing error in a single catch clause and call it a day, but not all errors are created equals, and you should treat it as such.

By learning different ways to catch an error, you can make reasonable catch clauses which easy to read, understand, and match your business needs.

In this article, we will learn different ways to catch errors from throwing functions. Let’s briefly introduce a throwing function and know what it uses to separate each catch clause.

Throwing Functions

To indicate that a function, method, or initializer can throw an error, Swift uses the throws keyword in the function’s declaration after its parameters.

func canThrowErrors() throws -> String
func cannotThrowErrors() -> String

But Swift has no way to specify the type of error that throws out. It can be any type that conforms to the Error protocol.

Lacking the way to specify the type means the caller must be responsible for differentiating errors and handling them. That’s why it is important to know what tools we have in catching.

Here is an example object which we will use throughout the article.

struct ErrorResponse: Codable { // 1
let code: Int
let message: String
}

enum APIError: Error { // 2
case failedResponse(ErrorResponse)
case unauthorized
case unknown
}

class APIClient { // 3
func makeRequest() throws {
// a throwing function.
}
}

1 A struct that represents an error object.
2 An error type with different cases.
3 A class with methods that can throw an error.

Pattern Matching

All catching mechanisms we will talk about today rely on one concept, pattern matching. If the code throws an error in the do clause, it will be matched against the catch clauses using a pattern (if provided) after that catch keyword, and that clause is selected to handle the error.

Her is the general form of a do-catch statement:

do {
    try expression
    // statements
} catch pattern 1 {
    // statements
} catch pattern 2 where condition {
    // statements
} catch pattern 3, pattern 4 where condition {
    // statements
} catch {
    // statements
}

I will guide you through some patterns that I find useful.

To catch any type of error thrown by the code in the do clause, you provide a catch clause without any pattern.

let client = APIClient()

do {
try client.makeRequest()
} catch { // 1
// 2
print(error)
}

1 A catch without pattern matches any error and binds the error to a local constant, error.
2 We can access error inside the catch clause without explicit declaration of error.

If a catch clause doesn’t have a pattern, the clause matches any error and binds the error to a local constant named error. This behavior is why we can reference the error in our print(error) without defining one (2).

Explicit error binding

If you already have a variable named error outside a do-catch statement, the local one will shadow the one outside the catch clause.

let client = APIClient()

// 1
let error = "Outer error"

do {
try client.makeRequest()
} catch {
// 2
print(type(of: error))
// APIError

1 An outer error constant of type string.
2 A local error constant shadows the error string outside the do-catch statement 2. This will print out the type of APIError, not String.

If you want to reference the outer error constant, you have to bind the local error to a new name explicitly. We can do that by using let.

let client = APIClient()

let error = "Outer error"

do {
try client.makeRequest()
} catch let localError { // 1
print(type(of: error))
// String

print(type(of: localError))
// APIError
}

1 We bind the error to a local constant named localError.

By specify let localError next to the catch clause, we tell Swift to bind an error to the localError constant.

Catch a particular type of error

Catch all clause handle any error thrown from the do clause the same way. It is easy, but you can’t do much of a handle since it is too generic. The best you can do might be to present users an alert with a generic message like «something went wrong».

So, you likely want to catch an error by its type. Swift provided a variety of patterns for you to use. I have grouped them into four categories.

Catch by error case
Catch by error case with an associated value
Catch by error type
Catch by error type and getting an error value

Catch by error case

You can catch a specific case of error by providing an error case in the pattern.

Here is an example where we want to handle an unauthorized error.

class APIClient {
...
func makeRequestThatNeedUnauthorization() throws {
throw APIError.unauthorized
}
}

let client = APIClient()

do {
try client.makeRequestThatNeedUnauthorization()
} catch APIError.unauthorized { // 1
// Called when error thrown is APIError.unauthorized
// TODO: Present a sign in screen
} catch {
print("others")
}

1 This catch clause will be called if the error thrown is a type of APIError.unauthorized. You might want to handle this specific case by presenting users with a sign-in screen.

Catch by error case with an associated value

Some errors case got associated value. We can access these values by specifying a tuple that contains one element for each associated value.

Here is an example where we try to read ErrorResponse from case failedResponse(ErrorResponse).

class APIClient {
...
func makeFailedRequest() throws {
let response = ErrorResponse(code: 404, message: "File not found")
throw APIError.failedResponse(response)
}
}

let client = APIClient()

do {
try client.makeFailedRequest()
} catch APIError.failedResponse(let errorResponse) { // 1
print(errorResponse)
// ErrorResponse(code: 404, message: "File not found")
} catch {
print("others")
}

1 Specify a tuple with the same number of an element with an associated value. In this case, we have only one associated value. We bind that value to an errorResponse constant.

Where clause

You can also provide a where clause to filter specific conditions of your retrieve value.

Here is an example where we have two catch clauses, one for handling ErrorResponse with 404 and one for other codes.

let client = APIClient()

do {
try client.makeFailedRequest()
} catch APIError.failedResponse(let errorResponse) where errorResponse.code == 404 { // 1
print("Handle only failed response with error code 404")
} catch APIError.failedResponse { // 2
print("Handle other failed response")
} catch {
print("others")
}

1 We add a condition to catch only a ErrorResponse with a code == 404 by put a condition after where clause.
2 Other responses with code other than 404 will fall into the second catch clause.

Catch by error type

So far, we learn how to catch specific cases of an error type. We might not want to handle some errors case by case but as a whole. An example I can think of is DecodingError. Each case of DecodingError tells us a reason why the decode operation failed. This is useful for debugging, but we might not need to handle this case by case since it usually means something wrong from your API, and this information is only goods for debugging.

The DecodingError error cases.

enum DecodingError {
case typeMismatch
case valueNotFound
case keyNotFound
case dataCorrupted
}

In this case, you might want to catch the error by its type. You can do that with a is pattern.

class APIClient {
...
func makeDataRequest() throws -> Data {
return "{"key": "value"}".data(using: .utf8)!
}
}

let client = APIClient()

do {
let data = try client.makeDataRequest()
let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: data)
} catch is DecodingError { // 1
print("DecodingError")
} catch is APIError {
print("APIError")
} catch {
print("others")
}

1 We use the is keyword follow by a type of error that we want to match against.

catch is DecodingError will match the DecodingError error regardless of its type.

Catch by error type and getting an error value

Even though we don’t want to handle DecodingError by case, we still want to know what kind of error it throws because we want to log it somewhere to fix the problem later. That’s means we want to get access to the error value.

To get the error value, we use let and as instead.

struct User: Decodable {
let name: String
}

class APIClient {
...
func makeDataRequest() throws -> Data {
return "{"key": "value"}".data(using: .utf8)!
}
}

let client = APIClient()

do {
let data = try client.makeDataRequest()
let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: data)
} catch let error as DecodingError { // 1
print("DecodingError: (error)")
// DecodingError: keyNotFound(CodingKeys(stringValue: "name", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "name", intValue: nil) ("name").", underlyingError: nil))
} catch is APIError {
print("APIError")
} catch {
print("others")
}

1 let error as DecodingError try to cast an error to DecodingError type, and if successful, bind that to an error local constant.

Mix and match

As mentioned earlier, you can have multiple catch clauses with different patterns. So you can mix and match any pattern you have learned into a single do-catch statement. You have seen this in previous examples already, but I want to highlight this again.

Multiple catch clauses

You can have different types of patterns for each catch clause.

do {
let data = try client.makeDataRequest()
let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: data)
} catch let error as DecodingError {
// Sending error log
} catch APIError.failedResponse(let errorResponse) where errorResponse.code == 404 {
// Handle only failed response with error code 404
} catch APIError.failedResponse {
// Handle other failed response
} catch is APIError {
// Handle the rest of APIError
} catch {
// Other errors
}

Multiple patterns

You can also have multiple patterns within a single catch clause by separate each pattern with a comma (,).

In the following example, we treat APIError.unauthorized and failed in decoding User object (DecodingError) as an unauthorized case and handle them together.

do {
let data = try client.makeDataRequest()
let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: data)
} catch APIError.unauthorized, is DecodingError { // 1
print("Unauthorized")
} catch {
// Other errors
}

1 We handle multiple patterns together with a comma (,).

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

Paul Hudson    September 23rd 2019    @twostraws

Swift works hard to make sure we can write safe software, which means it eliminates many opportunities for our code to fail. One of the ways it accomplishes this is by letting us catch errors when risky code doesn’t run according to plan, and in this article I’m going to walk through how that works and how to use it in your own code.

The Swift approach: try, catch, do and throw

If we wanted to load a file from a URL into a `Data` instance, we might write code like this:

let contents: Data?
do {
    contents = try Data(contentsOf: someURL)
} catch {
    contents = nil
}

That illustrates three of the five new keywords you’ll need to learn.

The fourth and fifth keywords are throw and throws, and we’ll look at them in depth now.

Please create a new Xcode project, using the Single View App template. You can name it whatever you feel like, and target whatever device you want – it doesn’t matter, because we’re not doing anything visual here.

Select ViewController.swift and add this new method:

func encrypt(_ str: String, withPassword password: String) -> String {
    // complicated encryption goes here
    let encrypted = password + str + password
    return String(encrypted.reversed())
}

That method is going to encrypt an string using the password that gets sent in. Well, it’s not actually going to do that – this article isn’t about encryption, so my «encryption» algorithm is pathetic: it puts the password before and after the input string, then reverses it. You’re welcome to add the complex encryption algorithm yourself later on!

Modify viewDidLoad() to call that method by adding this:

let encrypted = encrypt("secret information!", withPassword: "12345")
print(encrypted)

When you run your app now, you’ll see «54321!noitamrofni terces54321» printed out in the Xcode terminal. Easy, right?

But there’s a problem: assuming you actually do put in a meaningful encryption algorithm, there’s nothing stopping users from entering an empty string for a password, entering obvious passwords such as «password», or even trying to call the encryption method without any data to encrypt!

Swift comes to the rescue: you can tell Swift that this method can throw an error if it finds itself in an unacceptable state, such as if the password is six or fewer characters. Those errors are defined by you, and Swift goes some way to ensuring you catch them all.

To get started, we need the throws keyword, which you add to your method definition before its return value, like this:

func encrypt(_ str: String, withPassword password: String) throws -> String {
    // complicated encryption goes here
    let encrypted = password + str + password
    return String(encrypted.reversed())
}

As soon as you do that, your code stops working: adding throws has actually made things worse! But it’s worse for a good reason: Swift’s try/catch system is designed to be clear to developers, which means you need to mark any methods that can throw using the try keyword, like this:

let encrypted = try encrypt("secret information!", withPassword: "12345")

…but even now your code won’t compile, because you haven’t told Swift what to do when an error is thrown. This is where the do and catch keywords come in: they start a block of code that might fail, and handle those failures. In our basic example, it might look like this:

do {
    let encrypted = try encrypt("secret information!", withPassword: "12345")
    print(encrypted)
} catch {
    print("Something went wrong!")
}

That silences all the errors, and your code runs again. But it’s not actually doing anything interesting yet, because even though we say encrypt() has the potential to throw an error, it never actually does.

How to throw an error in Swift

Before you can throw an error, you need to make a list of all the possible errors you want to throw. In our case, we’re going to stop people from providing empty passwords, short passwords and obvious passwords, but you can extend it later.

To do this, we need to create an enum that represents our type of error. This needs to build on the built-in Error enum, but otherwise it’s easy. Add this before class ViewController:

enum EncryptionError: Error {
    case empty
    case short
}

That defines our first two encryption error types, and we can start using them immediately. As these are preconditions to running the method, we’re going to use the new guard keyword to make our intentions clear.

Put this at the start of encrypt():

guard password.count > 0 else { throw EncryptionError.empty }
guard password.count >= 5 else { throw EncryptionError.short }

If you run the app now nothing will have changed, because we’re providing the password «12345». But if you set that to an empty string, you’ll see «Something went wrong!» printed in the Xcode console, showing the error.

Of course, having a single error message isn’t helpful – there are several ways the method call can fail, and we want to provide something meaningful for each of them. So, modify the try/catch block in viewDidLoad() to this:

do {
    let encrypted = try encrypt("secret information!", withPassword: "")
    print(encrypted)
} catch EncryptionError.empty {
    print("You must provide a password.")
} catch EncryptionError.short {
    print("Passwords must be at least five characters, preferably eight or more.")
} catch {
    print("Something went wrong!")
}

Now there are meaningful error messages, so our code is starting to look better. But you may notice that we still need a third catch block in there even though we already caught both the .empty and .ehort cases.

Swift wants exhaustive try/catch error handling

If you recall, I said «Swift goes some way to ensuring you catch them all» and here’s where that becomes clear: we’re catching both errors we defined, but Swift also wants us to define a generic catch all to handle any other errors that might occur. We don’t tell Swift what kind of error our encryption method might throw, just that it throws something, so this extra catch-all block is required.

This does have one downside: if you add any future values to the enum, which we’re about to do, it will just drop into the default catch block – you won’t be asked to provide any code for it as would happen with a switch/case block.

We’re going to add a new value to our enum now, to detect obvious passwords. But we’re going to use Swift’s super-powerful enums so that we can return a message along with the error type. So, modify the EncryptionError enum to this:

enum EncryptionError: Error {
    case empty
    case short
    case obvious(String)
}

Now when you want to throw an error of type EncryptionError.obvious you must provide a reason.

guard password != "12345" else { throw EncryptionError.obvious("I've got the same passcode on my luggage!") }

Obviously you don’t want to provide hundreds (or thousands!) of guard statements to filter out obvious passwords, but hopefully you remember how to use UITextChecker to do spell checking – that would be a smart thing here!

That’s our basic do/try/throw/catch Swift example complete. You might look at the try statement and think it useless, but it’s primarily there to signal to developers «this call might fail.» This matters: when a try calls fails, execution immediately jumps to the catch blocks, so if you see try before a call it signals that the code beneath it might not get called.

There’s one more thing to discuss, which is what to do if you know a call simply can’t fail, for whatever reason. Now, clearly this is a decision you need to make on a case-by-case basic, but if you know there’s absolutely no way a method call might fail, or if it did fail then your code was so fundamentally broken that you might as well crash, you can use try! to signal this to Swift.

When you use the try! keyword, you don’t need to have do and catch around your code, because you’re promising it won’t ever fail. Instead, you can just write this:

let encrypted = try! encrypt("secret information!", withPassword: "12345")
print(encrypted)

Using the try! keyword communicates your intent clearly: you’re aware there’s the theoretical possibility of the call failing, but you’re certain it won’t happen in your use case. For example, if you’re trying to load the contents of a file in your app’s bundle, any failure effectively means your app bundle is damaged or unavailable, so you should terminate.

That’s all for error handling in Swift. If you’d like to learn about how Swift handles try/finally you should read my article on Swift’s defer keyword.

Learn how to handle your errors and crashes gracefully in Swift with try catch blocks and more! You’ll see the most common error handling code samples below. If you’d like a longer read, check out the Swift error handling documentation.

Swift Try Catch

When you’re coding, you’ll see methods that have the throws keyword. This indicates that the method may raise an error and as a best practice, you should gracefully handle the error and show an appropriate error message to the user. If you don’t catch the error, then your app will crash!

Here’s an example of the Swift do-try-catch syntax:

do {
    // Create audio player object
    audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
            
    // Play the sound
    audioPlayer?.play()
}
catch {
    // Couldn't create audio player object, log the error
    print("Couldn't create the audio player for file (soundFilename)")
}

Let’s walk through the code:

do – This keyword starts the block of code that contains the method that can potentially throw an error.

try – You must use this keyword in front of the method that throws. Think of it like this: “You’re trying to execute the method.

catch – If the throwing method fails and raises an error, the execution will fall into this catch block. This is where you’ll write code display a graceful error message to the user.

Use this pattern to handle any potential errors caused by a method that throws.

Using Try? and Try!

You can still call a method that throws without using the do-try-catch syntax.

// Create audio player object
audioPlayer = try? AVAudioPlayer(contentsOf: soundURL)
            
// Play the sound
audioPlayer?.play()

If you use the try? keyword instead of the basic try, you’ll get nil instead of the thrown error. In the code above, if the AVAudioPlayer object can’t be created, then nil will be assigned to the audioPlayer variable.

Finally, if you’re 100% sure that there will be no error thrown, even though it’s a method that is marked as throws, then you can use the try! keyword instead of the basic try.

// Create audio player object
audioPlayer = try! AVAudioPlayer(contentsOf: soundURL)
            
// Play the sound
audioPlayer?.play()

Doing this will completely disregard the fact that an error might be thrown by the method and if an error actually occurs and you don’t have the do catch blocks, then your app will probably crash.

Creating your own Swift Error type

If you’d like to define your own error type, you can use an enum and the Error protocol like this:

enum BankAccount: Error {
    case insufficientFunds
    case invalidTransaction
    case duplicateTransaction
    case unknown
}

Throwing Errors

After you define your own error type, you can start using it in your methods like this:

func withdrawCash (amount: Int) throws {
    if funds - amount < 0 {
        throw BankAccount.insufficientFunds
    }
    else {
        funds -= amount
    }
}

Using the throw keyword, your method will return and raise the error. Notice that in your function declaration, you also need to indicate that the function can raise errors by specifying the throws keyword.

When you throw the error, it’s like the return keyword. Execution stops at the throw keyword and returns to the caller.

Понравилась статья? Поделить с друзьями:
  • Swi ошибка ивеко стралис
  • Swf2 read tool ошибка 10061
  • Swf2 read tool result error
  • Swf2 read tool 151 http protocol error 404
  • Swegon gold ошибки