From the documentation:
Error Handling
Error handling is the process of responding to and recovering from
error conditions in your program. Swift provides first-class support
for throwing, catching, propagating, and manipulating recoverable
errors at runtime.
...
Representing and Throwing Errors
In Swift, errors are represented by values of types that conform to
the ErrorType
protocol. This empty protocol indicates that a type can
be used for error handling.
(Note: ErrorType
has been renamed to Error
in Swift 3)
So with try/catch
you handle Swift errors (values of types that conform to the ErrorType
protocol) which are throw
n.
This is completely unrelated to runtime errors and runtime exceptions
(and also unrelated to NSException
from the Foundation library).
Note that the Swift documentation on error handling does not even use the
word "exception", with the only exception (!) in (emphasis mine) in:
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.
The unwrapping of optionals which are nil
does not throw
a
Swift error (which could be propagated) and cannot be handled with
try
.
You have to use the well-known techniques like
optional binding, optional chaining, checking against nil
etc.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…