| Start |
|---|
| Error handling basics Functions in Swift may return values, throw errors (opens new window), or both: Any value which conforms to the ErrorType protocol (opens new window) (including NSError objects) can be thrown as an error. Enumerations (opens new window) provide a convenient way to define custom errors: An error indicates a non-fatal failure during program execution, and is handled with the specialized control-flow constructs Errors can be caught with Any function which can throw an error must be called using |
| Catching different error types Let's create our own error type for this example. The Do-Catch syntax allows to catch a thrown error, and automatically creates a constant named You can also declare a variable yourself: It's also possible to chain different Here the Do-Catch will first attempt to cast the error as a In Swift 3, no need to explicitly downcast to NSError. |
Catch and Switch Pattern for Explicit Error Handling In the client class: |
| Disabling Error Propagation The creators of Swift have put a lot of attention into making the language expressive and error handling is exactly that, expressive. If you try to invoke a function that can throw an error, the function call needs to be preceded by the try keyword. The try keyword isn't magical. All it does, is make the developer aware of the throwing ability of the function. 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 is appropriate to disable error propagation. |
| Create custom Error with localized description Create Create Handle error: RemarksFor more information about errors, see The Swift Programming Language (opens new window). |
Read Article
https://develop.horje.com/learn/1434/reference