From 9359b1aa3664ca568b80a3bb067b929f26c12262 Mon Sep 17 00:00:00 2001 From: Ishan Chhabra <32290367+ishan-chhabra@users.noreply.github.com> Date: Sun, 27 Jan 2019 08:16:41 +0530 Subject: [PATCH] Add Section About Error Handling (#33365) * Add Section About Error Handling * fix: added front matter block --- guide/english/swift/error-handling/index.md | 37 +++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 guide/english/swift/error-handling/index.md diff --git a/guide/english/swift/error-handling/index.md b/guide/english/swift/error-handling/index.md new file mode 100644 index 0000000000..0384d08dcd --- /dev/null +++ b/guide/english/swift/error-handling/index.md @@ -0,0 +1,37 @@ +--- +title: Error Handling +--- + +# Error Handling + +You represent errors using any type that adopts the `Error` protocol. + +```Swift +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. + +```swift +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. + +```swift +do { + let printerResponse = try send(job: 1040, toPrinter: "Bi Sheng") + print(printerResponse) +} catch { + print(error) +} +// Prints "Job sent" +```