Error Handling
Error handling is the process of responding to an error and returning from an error. Swift provides the first type of error support, including throwing, capturing, transmitting, and controlling recoverable errors at run time.
Some functions and methods are not always guaranteed to execute all code or produce useful output. A nullable type is used to indicate that a value may be empty, but when the function fails, it can usually be used to determine the cause of the failure, so the code can respond correctly to the failure. in Swift, this is called throwing a function or throwing a method.
Wrong representation
In Swift, the error is ErrorType
represented by a value that conforms to the agreement. Swift enumeration is especially useful for combining a series of related errors together, while associating some related values with errors. Therefore ErrorType
, the compiler automatically implements the corresponding composition for the Swift enumeration type that implements the protocol.
Simulation of the error condition of the vending machine enum Vendingmachineerror:errortype { //commodity does not exist when case invalidselection //Put money when case Insufficientfunds (required:double) //Goods Sold out case Outofstock}
An error is thrown by adding a keyword after the argument to the function or method declaration throws
, indicating that the function or method can throw an error. If you specify a return value, you can put the throws
keyword in front of the return arrow (-).
Func Canthrowerror () throw, Stringfunc cannotthrowerror (), String
When calling a throw function, precede the call with the try
. This keyword indicates that the function can throw an error.
Let favoritesnacks = [ "Alice": "Chips", "Bob": "Licorice", "Eve": "Pretzels",]func Buyfavoritesnack ( Person:string) throws {let snackname = Favoritesnacks[person]?? "Candy Bar" try Vend (itemname:snackname)}
catching and handling errors
Using the Do-catch statement to capture and handle errors
Do { Try Vend (itemname: "Candy Bar") ///If the Vend throws an error, it is passed into the catch //can be handled in the catch to do what should be done after the error does not cause a run-time error} Catch vendingmachineerror.invalidselection { print ("Invalid Selection")} catch Vendingmachineerror.insufficientfunds (Let amountrequired) { print ("insufficient funds. Please insert an additional $\ (amountrequired). ")} Catch Vendingmachineerror.outofstock { print ("Out of Stock")}//insufficient funds. Please insert an additional $0.25.
Note: error handling in Swift is similar to exception handling in other languages, using the try
, catch
and throw
keywords. But unlike these languages, including objective-c--, Swift does not expand the call stack, which can lead to significant performance losses. Therefore, the throw
performance of the statement in Swift can be almost the return
same as the statement.
Prohibit error propagation
At run time, there are several situations where throwing a function does not actually throw an error. In these cases, you can use forced-try
an expression to invoke the throw function or method, which is used try!
instead try
.
By try!
calling the throw function or method, the error transfer is forbidden and the call wrapper is asserted at run time, so that no error is thrown. If the error is actually thrown, a run-time error is triggered.
Enum Customerror:errortype {case someerror}func willonlythrowiftrue (value:bool) throws { If value {throw Custo Merror.someerror}}do { try Willonlythrowiftrue (true)} catch { print ("Error")}try! Willonlythrowiftrue (True) //Run-time error
Finishing Action
Use the defer statement to execute a series of statements. This allows you to perform some necessary finishing touches, whether or not an error occurs. This includes closing open file descriptors and freeing all manually allocated memory.
defer
Statement to defer execution until the current domain is exited. defer
The statement includes defer
the keyword and the statement to be executed later. the deferred statement may not contain any code that transfers the execution process to the outside, such break
as return
a statement, or by throwing an error. The execution of deferred operations is reversed in the order in which they are defined, that is, the code in the first defer
statement executes after the code in the second defer
statement.
Func Processfile (filename:string) throws { if exists (filename) {let file = open (filename) defer { Close (file) } while a let line = Try File.readline () {// write file } //defer in the last call. Whether or not to throw an error }}
Learn Swift-error handling