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.
throw
(which is what causes errors to be propagated from within such a function) is the same thing that happens when you force-unwrap anil
. I think I read somewhere that it is implemented as anassert()
. – ShrewdErrorType
which are thrown). That is completely unrelated to runtime errors or exceptions. (The documentation does not even mention the word "exception" in connection with throw/try/catch, only "Error handling".) – Dunsinanetry
/catch
) to deal with exception handling. – Shrewd