1. 程式人生 > >Swift Course: Error Handling Fundamentals

Swift Course: Error Handling Fundamentals

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 do

-catch statement, handle the error as an optional value, or assert that the error will not occur. Each approach is described in a section 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 does not 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.