欠如

来世は貝になりたい

ツアーの旅Error Handling

どうもツアーの旅です。 今日のツアーテーマはError Handlingについてです。

まずはじめに エラーハンドリングとは何かですが IT用語辞典によるところ エラーハンドリング(error handling)とは、本来の処理が正常に終了しなかった際に発生するエラーをトラップし、プログラムを正常な状態に復帰させる処理。 みたいです。

You represent errors using any type that adopts the Error protocol.

エラープロトコルを採用しているすべてのタイプを使用してエラーを表現します。

enum PrinterError: Error { case outOfPaper case noToner case onFire }

Use throw to throw an error and throws to mark a function that can throw an error. If you throw an error in a function, the function returns immediately and the code that called the function handles the error.

throwを使用してエラーをスローし、スローしてエラーをスローする可能性のある関数をマークします。   関数にエラーを投げた場合、関数はすぐに戻り、関数を呼び出したコードがエラーを処理します。

func send(job: Int, toPrinter printerName: String) throws -> String { if printerName == “Never Has Toner” { throw PrinterError.noToner } return “Job sent” }

There are several ways to handle errors. One way is to use do-catch. Inside the do block, you mark code that can throw an error by writing try in front of it. Inside the catch block, the error is automatically given the name error unless you give it a different name.

エラーを処理するにはいくつかの方法があります。 1つの方法は、do-catchを使用することです。   doブロックの中で、その前にtryを書くことによってエラーを投げることができるコードをマークします。 catchブロックの内部では、別の名前を指定しない限り、エラーには自動的に名前エラーが与えられます。

do { let printerResponse = try send(job: 1040, toPrinter: “Bi Sheng”) print(printerResponse) } catch { print(error) }

実行すると1つ前のfunc sendのエラーが回避されて"Job sent"が表示されます。

You can provide multiple catch blocks that handle specific errors. You write a pattern after catch just as you do after case in a switch.

特定のエラーを処理する複数のキャッチブロックを提供できます。   あなたは、スイッチのケースの後と同じように、キャッチ後にパターンを書きます。

do { let printerResponse = try send(job: 1440, toPrinter: “Gutenberg”) print(printerResponse) } catch PrinterError.onFire { print(“I’ll just put this over here, with the rest of the fire.”) } catch let printerError as PrinterError { print(“Printer error: (printerError).”) } catch { print(error) }

Another way to handle errors is to use try? to convert the result to an optional. If the function throws an error, the specific error is discarded and the result is nil. Otherwise, the result is an optional containing the value that the function returned.

エラーを処理する別の方法はtryを使うことです? 結果をオプションに変換します。 関数がエラーをスローすると、特定のエラーは破棄され、結果はnilになります。 それ以外の場合、結果は、関数が戻した値を含むオプションです。

let printerSuccess = try? send(job: 1884, toPrinter: “Mergenthaler”) let printerFailure = try? send(job: 1885, toPrinter: “Never Has Toner”)

Use defer to write a block of code that is executed after all other code in the function, just before the function returns. The code is executed regardless of whether the function throws an error. You can use defer to write setup and cleanup code next to each other, even though they need to be executed at different times.

deferを使用して、関数内の他のすべてのコードの後、関数が返される直前に実行されるコードブロックを記述します。 コードは、関数がエラーをスローするかどうかに関係なく実行されます。 異なるタイミングで実行する必要がある場合でも、deferを使用して、セットアップコードとクリーンアップコードを互いに隣に書き込むことができます。

var fridgeIsOpen = false let fridgeContent = [“milk”, “eggs”, “leftovers”]

func fridgeContains(_ food: String) -> Bool { fridgeIsOpen = true defer { fridgeIsOpen = false }

let result = fridgeContent.contains(food)
return result

} fridgeContains(“banana”) print(fridgeIsOpen)