Swift Error Handling
During program execution you always run into unexpected situations: files not found, network disconnection, wrongly formatted user input.
Swift uses an explicit error-handling mechanism to describe these recoverable failures, writing "this operation may fail" directly into the function signature so the compiler helps you watch every call site.
This article covers the Error protocol, throw / throws / try / do-catch, try? / try!, defer, rethrows, and Result, and finally explains when to use errors and when optionals are enough.
Why error handling is needed
Without an error-handling mechanism, functions usually can only report failure via special return values, such as -1, an empty string, or nil.
The problem with this approach is that callers easily forget to check, and the information about "why it failed" is lost in transit.
Swift's approach is to write the failure into the function signature; the caller must explicitly state it with try, and the compiler checks whether you handled the error.
| Ways of reporting failure | What is returned on failure | What the caller needs to do | Applicable scenarios |
|---|---|---|---|
| Special return value | An agreed sentinel value, such as -1 | Remember to check it yourself | Failure has a single meaning, and the sentinel doesn't conflict with normal results |
| Optional types | nil | Unwrap with if let or ?? | Only care about "whether there's a value", not the failure reason |
| throws error | Throw a value conforming to Error | Handle with try or propagate further | The failure reason matters to the caller and may be recoverable |
The Error protocol and custom error types
Error types in Swift must conform to the Error protocol.
This protocol has no required implementations; it's just a marker indicating the type can be thrown as an error.
The most common way to define one is with an enum, because an enum can clearly list all possible failure reasons and then handle them one by one with switch or catch.
Defining errors with an enum
The following example defines a network error type and marks a possibly failing function with throws.
Example
import Foundation
// Conforming to Error is all it takes to become an error type
enum
NetworkError
:
Error
{
case
invalidURL
(
String
)
// Associated value: the URL that failed
case
timeout
(
seconds
:
Int
)
// Associated value: the number of seconds timed out
case
serverError
(
code
:
Int
)
// Associated value: the HTTP status code
}
// Mark a possibly failing function with throws
func fetchData
(
from url
:
String
)
throws
String
{
if
url.
isEmpty
{
throw
NetworkError.
invalidURL
(
url
)
}
if
url.
contains
(
"timeout"
)
{
throw
NetworkError.
timeout
(
seconds
:
30
)
}
return
"RUNOOB homepage data"
}
do
{
let data
=
try
fetchData
(
from
:
"https://www.runoob.com"
)
(
"Fetch succeeded: (data)"
)
}
catch
{
(
"Fetch failed: (error)"
)
}
Running result:
获取成功:RUNOOB 首页数据
In a function signature, throws is written after the parameter list and before the return arrow.
It tells the compiler that calling this function requires try, otherwise compilation fails.
Errors with associated values and pattern matching
An enum's associated values let errors carry contextual information, such as the specific failing URL, timeout seconds, and status code.
In catch you can use the same pattern-matching syntax as switch to extract this information.
Example
import Foundation
enum
NetworkError
:
Error
{
case
invalidURL
(
String
)
case
timeout
(
seconds
:
Int
)
case
serverError
(
code
:
Int
)
}
func fetchData
(
from url
:
String
)
throws
String
{
if
url.
isEmpty
{
throw
NetworkError.
invalidURL
(
url
)
}
if
url.
contains
(
"timeout"
)
{
throw
NetworkError.
timeout
(
seconds
:
30
)
}
return
"RUNOOB homepage data"
}
// Catch by error type separately, noting the order: specific first, general later
func check
(
_ url
:
String
)
{
do
{
let data
=
try
fetchData
(
from
:
url
)
(
"success: (data)"
)
}
catch
NetworkError.
invalidURL
(
let value
)
{
(
"URL is empty: "(value)""
)
}
catch
NetworkError.
timeout
(
let seconds
)
{
(
"Timed out after (seconds) seconds"
)
}
catch
NetworkError.
serverError
(
let code
)
{
(
"Server error, status code (code)"
)
}
catch
{
(
"Other error: (error)"
)
}
}
check
(
""
)
check
(
"https://www.runoob.com/timeout"
)
check
(
"https://www.runoob.com"
)
Running result:
地址为空:""
超时 30 秒
成功:RUNOOB 首页数据
The last one without a pattern catch is equivalent to switch inside default, used as a fallback. Without it, Swift considers your catch not to cover all errors and reports a compile error.
Providing readable text with LocalizedError
Printing an error value directly gives a debug form like invalidURL(""), which isn't suitable for showing to users.
Conforming to LocalizedError and implementing errorDescription makes localizedDescription return a human-readable description.
Example
import Foundation
enum
RunoobError
:
LocalizedError
{
case
notFound
(
name
:
String
)
// Description text shown to the user
var errorDescription
:
String
?
{
switch
self
{
case
.
notFound
(
let name
)
:
return
"Page not found: (name)"
}
}
}
do
{
throw
RunoobError.
notFound
(
name
:
"swift-tutorial"
)
}
catch
{
(
error.
localizedDescription
)
}
Running result:
找不到页面:swift-tutorial
throw and throws
throw is used to throw an error, and throws is used to declare "this function may throw an error"; the two form a pair.
Only functions marked throws and the inside of do blocks can contain throw.
Once throw is executed, the current function stops immediately, subsequent code doesn't run, and control returns to the caller.
Example
import Foundation
enum
RunoobError
:
Error
{
case
notFound
(
String
)
}
func process
(
_ step
:
Int
)
throws
String
{
(
"Step (step) starts"
)
if
step
==
2
{
throw
RunoobError.
notFound
(
"Step (step)"
)
// After throwing, this function stops immediately
}
(
"Step (step) completed"
)
return
"OK"
}
for
step in
1
...
3
{
do
{
(
try
process
(
step
)
)
}
catch
{
(
"Interrupted: (error)"
)
}
}
Running result:
步骤 1 开始
步骤 1 完成
OK
步骤 2 开始
中断:notFound("步骤 2")
步骤 3 开始
步骤 3 完成
OK
From the output you can see step 2 stops right at the throw, and the subsequent "Step 2 completed" and the return value never appear.
But the loop itself isn't broken; step 3 runs as usual because the error was caught by do-catch.
try and do-catch
When calling a throws function you must write try, which syntactically reminds you "this may fail".
The most common way to handle it is do-catch: put possibly failing code in the do block, and handle errors uniformly in the catch block.
If any line in the do block throws, control jumps to catch and the remaining statements in the do block don't execute.
catch matching order
catch matches from top to bottom; the first matching branch is executed and later branches aren't tried.
Therefore put specific errors first and the general catch last.
| catch syntax | Match scope | Description |
|---|---|---|
| catch NetworkError.timeout(let s) | A specific enum case | Extract associated value s; other errors continue matching downward |
| catch is NetworkError | A certain error type | Don't care about the specific case, only check the type |
| catch let error as NetworkError | A certain error type with binding | Bind the error to a specific type then use it |
| catch | All remaining errors | Implicitly binds to local variable error; must be placed last |
Swift errors are not "exceptions". They don't automatically bubble up to arbitrary places; they can only propagate level by level along the call chain, or be do-catch handled in place.
try? and try!
In some situations you don't need to distinguish the failure reason, only want to know "success or failure"; you can use try? to turn the result into an optional.
try? returns a wrapped optional on success and nil on failure, discarding the original error information.
try! asserts "this call definitely won't fail"; if it actually fails, the program crashes.
Example
import Foundation
enum
ParseError
:
Error
{
case
notANumber
(
String
)
}
func toNumber
(
_ text
:
String
)
throws
Int
{
guard let value
=
Int
(
text
)
else
{
throw
ParseError.
notANumber
(
text
)
}
return
value
}
// try? wraps the result in an optional, giving nil on failure
let a
=
try
?
toNumber
(
"42"
)
let b
=
try
?
toNumber
(
"runoob"
)
(
a
??
1
)
(
b
==
nil
)
// try! asserts certain success; failure crashes directly
let c
=
try
!
toNumber
(
"100"
)
(
c
)
Running result:
42
true
100
| Syntax | Behavior on failure | Applicable scenarios |
|---|---|---|
| try | Hand the error to the upper layer | Need to distinguish the failure reason or propagate upward |
| try? | Return nil | Don't care about the reason, only success or failure |
| try! | Trigger a runtime trap, program crashes | Only for situations that logically can't fail, such as tests or parsing constants |
Do not confuse try! Treat it as a shortcut for "too lazy to write do-catch". It trades compile-time checks for runtime crash risk, so use it cautiously in production code.
defer cleanup actions
defer declares a block of code that "will definitely execute before leaving the current scope", whether the function returns normally or throws.
It's suitable for paired cleanup: close after opening a file, unlock after locking, log after starting a task.
Example
import Foundation
enum
FileError
:
Error
{
case
emptyName
}
func readFile
(
_ name
:
String
)
throws
String
{
(
"1. Open file: (name)"
)
defer
{
// Whether returning normally or throwing, this will execute
(
"3. Close file: (name)"
)
}
(
"2. Read content"
)
if
name.
isEmpty
{
throw
FileError.
emptyName
}
return
"RUNOOB document content"
}
do
{
(
try
readFile
(
"runoob.txt"
)
)
}
catch
{
(
"Failed: (error)"
)
}
Running result:
1. 打开文件:runoob.txt
2. 读取内容
3. 关闭文件:runoob.txt
RUNOOB 文档内容
A scope can have multiple defers; they execute in reverse declaration order, so the last declared runs first.
Example
import Foundation
func runoobTask
(
)
{
defer
{
(
"A"
)
}
defer
{
(
"B"
)
}
defer
{
(
"C"
)
}
(
"Start"
)
}
runoobTask
(
)
Running result:
开始
C
B
A
defer executes when leaving the scope, not "when the function ends". Written inside if or in a loop body, defer, it triggers when that block ends.
Error propagation and rethrows
When a function doesn't handle an error itself, it can declare throws in its signature and pass the error unchanged to the caller; this is error propagation.
Every level in the propagation chain must write try, until some level handles it with do-catch.
Example
import Foundation
enum
UserError
:
Error
{
case
emptyID
(
Int
)
case
notFound
(
Int
)
}
// The low-level function detects and throws the error
func loadName
(
_ id
:
Int
)
throws
String
{
guard id
0
else
{
throw
UserError.
emptyID
(
id
)
}
guard id
==
1
else
{
throw
UserError.
notFound
(
id
)
}
return
"runoob"
}
// The middle function doesn't handle it, only declares throws to let the error propagate upward
func loadProfile
(
_ id
:
Int
)
throws
String
{
let name
=
try
loadName
(
id
)
return
"User: (name)"
}
// The outermost layer handles it uniformly
for
id in
[
1
,
2
,
0
]
{
do
{
(
try
loadProfile
(
id
)
)
}
catch
UserError.
emptyID
(
let value
)
{
(
"Invalid ID: (value)"
)
}
catch
{
(
"Other error: (error)"
)
}
}
Running result:
用户:runoob
其他错误:notFound(2)
编号无效:0
rethrows is for higher-order functions that "take function parameters".
It means: the function itself produces no errors; only when the passed-in closure throws does it propagate the error further.
Example
import Foundation
enum
ParseError
:
Error
{
case
notANumber
(
String
)
}
// rethrows: this function only throws if the passed-in closure throws
func runoobMap
(
_ values
:
[
Int
]
, transform
:
(
Int
)
throws
Int
)
rethrows
[
Int
]
{
var result
:
[
Int
]
=
[
]
for
value in values
{
result.
append
(
try
transform
(
value
)
)
}
return
result
}
// Pass a non-throwing closure: no try needed at the call site
let doubled
=
runoobMap
(
[
1
,
2
,
3
]
)
{
$
0
2
}
(
doubled
)
// Pass a throwing closure: try is required at the call site
do
{
let checked
=
try
runoobMap
(
[
1
,
2
,
3
]
)
{
value in
if
value
==
2
{
throw
ParseError.
notANumber
(
"(value)"
)
}
return
value
}
(
checked
)
}
catch
{
(
"Error: (error)"
)
}
Running result:
[2, 4, 6]
出错:notANumber("2")
The benefit of rethrows is preserving caller flexibility: when passing a non-throwing closure, the call site doesn't need try and isn't forced into do-catch.
Using rethrows a function, whose closure parameter must be marked throws, and whose body can't itself write throw。
Result type
Result is an enum that packs "success" and "failure" into a single value (SE-0235, introduced in Swift 5).
It's suitable when errors need to be saved, passed around, or handled later, such as asynchronous callbacks or storing errors in an array.
Example
import Foundation
enum
ParseError
:
Error
{
case
notANumber
(
String
)
}
// Return a Result instead of throwing: the caller gets a value that can be passed around freely
func fetchScore
(
_ name
:
String
)
Result
<
Int, ParseError
{
guard let score
=
Int
(
name
)
else
{
return
.
failure
(
.
notANumber
(
name
)
)
}
return
.
success
(
score
)
}
// Handle both outcomes with switch
switch
fetchScore
(
"88"
)
{
case
.
success
(
let score
)
:
(
"Score: (score)"
)
case
.
failure
(
let error
)
:
(
"Failed: (error)"
)
}
// get() converts a Result back to a throws call
do
{
let score
=
try
fetchScore
(
"runoob"
)
.
get
(
)
(
score
)
}
catch
{
(
"get threw: (error)"
)
}
Running result:
分数:88
get 抛出:notANumber("runoob")
Result also provides several common methods for transforming the result without unwrapping a switch.
| members | Purpose |
|---|---|
| get() | Returns the associated value on success, throws the error on failure, reconnecting to the throws world |
| map(_:) | Transforms the associated value on success, passes through unchanged on failure |
| flatMap(_:) | Executes a closure returning Result on success, for chaining operations |
| mapError(_:) | Transforms the error type on failure |
| case success / failure | Uses pattern matching to extract the corresponding result |
After async / await became widespread, async scenarios prefer using async throws functions directly, rather than passing Resultin callbacks. But Result remains irreplaceable when you need to "store the result".
Choosing between errors and optionals
Both optionals and errors can express "no value obtained", but they convey different amounts of information.
The official documentation's criterion is: whether the failure reason matters to the caller.
If it's a single meaning like "not found" or "no next", optionals are lighter; if failure can have multiple reasons and the caller needs to handle them differently, use throws.
Example
import Foundation
// With only two outcomes "found / not found", an optional is enough
func findUser
(
_ name
:
String
)
String
?
{
return
name
==
"runoob"
?
"RUNOOB admin"
:
nil
}
enum
LoginError
:
Error
{
case
userNotFound
(
String
)
case
wrongPassword
(
String
)
}
// When failure reasons are distinguishable and the caller must handle them separately, use throws
func login
(
user
:
String, password
:
String
)
throws
String
{
guard user
==
"runoob"
else
{
throw
LoginError.
userNotFound
(
user
)
}
guard password
==
"runoob123"
else
{
throw
LoginError.
wrongPassword
(
user
)
}
return
"Login successful, welcome (user)"
}
(
findUser
(
"runoob"
)
??
"No such user found"
)
(
findUser
(
"guest"
)
??
"No such user found"
)
do
{
(
try
login
(
user
:
"runoob"
, password
:
"runoob123"
)
)
}
catch
{
(
error
)
}
Running result:
RUNOOB 管理员
查无此人
登录成功,欢迎 runoob
| Criterion | Choose optional | Choose throws error |
|---|---|---|
| Number of failure reasons | Only one meaning | Multiple reasons, need to distinguish |
| Whether the caller needs to recover | No, just give up if no value | Need to retry or notify the user based on the reason |
| Whether it carries context | No extra information needed | Need details like URL, status code, ID |
| Burden on the call site | A single ?? or if let is enough | Requires do-catch or upward propagation |
Another case is "failure due to a program bug, unrecoverable", such as array index out of bounds or force-unwrapping nil.
Swift handles such problems with a runtime trap, terminating the program directly without entering the error-handling flow.
Don't use error handling to mask logic errors. If a condition isn't met, it means the program is written wrong; use precondition or fatalError is more honest.
Common questions
Below are several problems beginners most often encounter when using error handling.
Why must catch have a patternless fallback branch
Because Swift's error types conform to the Error protocol, the compiler can't know all possible error types that may be thrown, so a fallback is required.
If you really only handle one kind of error and want others to propagate upward, mark the function throws, catch only the target error in do-catch, and rethrow the rest.
Can a do block contain multiple trys?
Yes. Any try that throws jumps to catch, and later trys that haven't executed naturally won't run.
If you want each operation handled independently, write a separate do-catch for each.
What information does try? lose
It discards the specific error value, leaving only "success or nil".
If later troubleshooting needs the failure reason, don't use try?; use do-catch to log the error instead.
Can a throws function's return value be ignored directly?
Yes, but you'll get a compiler warning. If you truly don't care about the return value, add @discardableResult to the function to eliminate the warning.
Must an error type be an enum?
Not necessarily; structs and classes can conform to Error too.
But enums are most natural for expressing "a finite set of failure reasons" and most convenient for pattern matching in catch, so they're used most in practice.
Can you write throw inside defer?
No. If a defer block must perform an operation that can fail, handle it yourself with do-catch inside the block.