There are 4
ways to handle errors in 1.Swift. You can pass the error that the function throws to the code that called the function, handle the error with the do-catch
statement, treat the error as an optional type, or assert that the error does not occur at all.
Error handling in 2.wift does not involve lifting the call stack, which is a computationally expensive process. For this, the throw
performance characteristics of a statement can be return
comparable to a statement.
3. A function marked with a throws
keyword is called the throwing function . If the function indicates a return value type, the throws
keyword needs to be written in ->
front of the arrow (). Only the throwing function can pass an error. Any error that is thrown inside a non-throwing function can only be handled inside the function.
4. You can use to try?
handle errors by converting an error to an optional value. If try?
an error is thrown when evaluating an expression, the value of the expression is nil
.
try? somethrowingfunction ()//equivalent to let Y:int? Do { trycatch { = Nil}
5. You can disable error delivery by writing in front of the expression try!
, which wraps the call in a run-time assertion where an assertion does not throw an error. If you actually throw an error, you will get a run-time error.
6. You can use defer
a statement to execute a series of statements when you are about to leave the current code block. This statement allows you to perform some necessary cleanup work, regardless of the way you leave the current block of code, whether it is due to throwing an error, or because of a statement such as return
or break
.
if exists (filename) { = open (filename) defer { close (file) } // The close (file) is called here, at the end of the scope. }
Swift Learning note 9--error control