Swift Error Handling

title: Error Handling

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.

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 docatch. Inside the doblock, 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.

do { let printerResponse = try send(job: 1040, toPrinter: "Bi Sheng") print(printerResponse) } catch { print(error) } // Prints "Job sent"

This article needs improvement. You can help improve this article. You can also write similar articles and help the community.