Throw and catch errors that use Cocoa's error types.
Overview
You use Swift's throw
statement and do
-catch
statement to throw and catch errors from Cocoa APIs. Swift imports Cocoa methods with error parameters as throwing methods, as described in About Imported Cocoa Error Parameters.
Catch Errors
In Swift, calling a method that throws requires explicit error handling. Because Cocoa methods with errors parameters are imported as throwing methods, you handle them using Swift's do
-catch
statement.
Here’s an example of how you handle an error when calling a method in Objective-C:
Here's how you handle the same error in Swift:
You can also use the do
-catch
statement to match on specific Cocoa error codes to differentiate possible failure conditions:
Throw Errors
You throw Cocoa errors by initializing a Cocoa error type and passing in the relevant error domain and code:
If Objective-C code calls a Swift method that throws an error, the error is automatically propagated to the error pointer argument of the bridged Objective-C method.
Throw and Catch Errors from Custom Error Domains
You use custom error domains in Cocoa to group related categories of errors. The example below uses the NS
macro to group error constants:
This example shows how to throw errors using that custom error type in Swift:
This example shows how to catch errors from a particular error domain and bring attention to unhandled errors from other error domains:
Handle Exceptions in Objective-C Only
In Objective-C, exceptions are distinct from errors. Objective-C exception handling uses the @try
, @catch
, and @throw
syntax to indicate unrecoverable programmer errors. This is distinct from the Cocoa pattern—described above—that uses a trailing NSError
parameter to indicate recoverable errors that you plan for during development.
In Swift, you can recover from errors passed using Cocoa’s error pattern, as described above in Catch Errors. However, there’s no safe way to recover from Objective-C exceptions in Swift. To handle Objective-C exceptions, write Objective-C code that catches exceptions before they reach any Swift code.