Error handling is the process of responding to an error and recovering from an error. Swift provides class-a citizen support for throwing, capturing, delivering, and manipulating recoverable errors at run time.
Some operations do not guarantee that all code is always executed or that useful results are always generated. An optional type can be used to indicate that a value is missing, but when an operation fails, it is best to know the reason for the failure, so that you can respond accordingly.
For example, if you have a task that reads data from a file on disk and processes it, there are a number of possible failures, including the fact that the file does not exist under the specified path, the file does not have a readable permission, or the file encoding format is incompatible. Distinguishing between these different failure scenarios allows the program to resolve and handle some errors, and then report the error to the user that it cannot resolve.
Attention
Error handling in SWIFT involves error-handling mode, which uses the Nserror in Cocoa and objective-c.
Represents and throws an error
In Swift, the error is represented by a value of the type that conforms to the error protocol. This null protocol indicates that the type can be used for error handling.
The enumeration type of Swift is particularly suitable for building a set of related error states, and the associated values of the enumeration can also provide additional information about the error state. For example, you can indicate an error state that can occur when you manipulate auto-trafficking in a game:
Enum Vendingmachineerror:error {
Case Invalidselection//invalid selection
Case Insufficientfunds (Coinsneeded:int)//Insufficient amount
Case Outofstock//out of stock
}
Throwing an error can let you indicate that an unexpected situation has occurred, causing the normal execution process to fail to execute. Throws an error using the Throw keyword. For example, the following code throws an error indicating that the vending machine also requires 5 coins:
Throw Vendingmachineerror.insufficientfunds (Coinsneeded:5)
Handling Errors
When an error is thrown, some code in the vicinity must be responsible for handling the error, such as correcting the problem, trying another way, or reporting an error to the user.
Swift Learning: Error handling