Rust Error Handling
Rust uses a unique error handling mechanism. There are no exceptions and no try/catch. It divides errors into two categories, handled in different ways:
- Unrecoverable Errors(Unrecoverable): a serious problem has occurred in the program logic; use the
panic!macro to terminate the program - Recoverable Errors(Recoverable): an operation may fail but can be handled; use
Resultenum
This design forces developers to handle possible errors at compile time, rather than discovering omissions at runtime.
1. Unrecoverable Errors: panic!
panic! The macro is used to indicate that the program has encountered a serious error from which it cannot continue. When called, it will:
- Print the error message and the location where it occurred
- Unwind the call stack and clean up resources
- Terminate the program
Example
fn
main
(
)
{
panic
!
(
"A serious error has occurred"
)
;
// The code below will never execute
println
!
(
"Hello, Rust"
)
;
}
Running result:
thread 'main' panicked at '发生了严重错误', src/main.rs:2:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
The two lines of output information:
- First line: the location of the panic (file name and line number), as well as the error message
- Second line: a hint on how to view the full backtrace
Viewing the Backtrace
Settings RUST_BACKTRACE=1 environment variables to see the full call stack, helping locate the root cause of the panic:
# Linux / macOS
RUST_BACKTRACE=1 cargo run
# Windows PowerShell
$env:RUST_BACKTRACE=1; cargo run
The backtrace output lists the complete call chain, from the point where the panic occurred main all the way to the function. This is very useful when a panic occurs deep in the call stack.
When to use it
panic!:Use it for logic errors (bugs) in your code that should never happen, such as out-of-bounds access, dereferencing a null pointer, or violating an immutability contract. For expected errors caused by external input, useResult。
2. Recoverable errors: Result
Result is an enum in the Rust standard library used to represent operations that may fail:
enum Result {
Ok(T), // 操作成功,包含结果值
Err(E), // 操作失败,包含错误信息
}
All functions in the Rust standard library that may fail return Result. For example, opening a file:
2.1 Handling Result with match
Example
use
std
::
fs
::
File
;
fn
main
(
)
{
let
f
=
File
::
open
(
"hello.txt"
)
;
match
f
{
Ok
(
file
)
=>
{
println
!
(
"File opened successfully: {:?}"
,
file
)
;
}
Err
(
error
)
=>
{
println
!
(
"Failed to open file: {}"
,
error
)
;
}
}
}
2.2 Simplifying handling with if let
When you only care about the success case,if let compared to match is more concise:
Example
use
std
::
fs
::
File
;
fn
main
(
)
{
let
f
=
File
::
open
(
"hello.txt"
)
;
if
let
Ok
(
file
)
=
f
{
println
!
(
"File opened successfully"
)
;
// use file here ...
}
else
{
println
!
(
"Failed to open file"
)
;
}
}
2.3 unwrap and expect: fast but dangerous
If you are sure the operation will not fail (or you do not want to handle errors during prototyping), you can use these two shortcuts:
| Method | Behavior | the panic message on failure |
|---|---|---|
.unwrap() |
returns the value on success T, and directly panics on failure panic! |
uses the default error message |
.expect("msg") |
returns the value on success T, and directly panics on failure panic! |
uses a custom error message (easier to debug) |
Example
use
std
::
fs
::
File
;
fn
main
(
)
{
// unwrap: panics on failure, using the default message
// thread 'main' panicked at 'called Result::unwrap() on an Err value: ...'
let
f1
=
File
::
open
(
"hello.txt"
)
.unwrap
(
)
;
// expect: panics on failure, using a custom message (recommended)
// thread 'main' panicked at 'cannot open the configuration file: ...'
let
f2
=
File
::
open
(
"hello.txt"
)
.expect
(
"cannot open the configuration file"
)
;
}
Note:In production code, prefer
expectinstead ofunwrap, because a custom error message lets you quickly locate the problem when a panic occurs. A better approach is to use the?operator to propagate the error to the caller.
3. Error propagation: the ? operator
In real development, when a function encounters an error it often does not want to handle it itself, but insteadpropagatesthe error to the caller. Rust provides the ? operator to simplify this operation.
3.1 Manual propagation vs. the ? operator
First look at the manual propagation approach -- verbose but clear:
Example
use
std
::
fs
::
File
;
use
std
::
io
::
{
self
,
Read
}
;
// propagate the error manually (tedious)
fn
read_file_manual
(
path
:
&
str
)
->
Result
<
String
,
io::
Error
{
let
f
=
File
::
open
(
path
)
;
// if opening fails, return Err
let
mut
file
=
match
f
{
Ok
(
file
)
=>
file
,
Err
(
e
)
=>
return
Err
(
e
)
,
// return the error early
}
;
let
mut
content
=
String
::
new
(
)
;
// if reading fails, return Err
match
file.read_to_string
(
&
mut
content
)
{
Ok
(
_
)
=>
Ok
(
content
)
,
Err
(
e
)
=>
Err
(
e
)
,
}
}
Use ? operator, the same logic can be simplified to:
Example
use
std
::
fs
::
File
;
use
std
::
io
::
{
self
,
Read
}
;
// using the ? operator (concise)
fn
read_file
(
path
:
&
str
)
->
Result
<
String
,
io::
Error
{
let
mut
file
=
File
::
open
(
path
)
?
;
// automatically returns Err on failure
let
mut
content
=
String
::
new
(
)
;
file.read_to_string
(
&
mut
content
)
?
;
// automatically returns Err on failure
Ok
(
content
)
}
You can also chain calls to simplify further:
fn read_file(path: &str) -> Result {
let mut content = String::new();
File::open(path)?.read_to_string(&mut content)?;
Ok(content)
}
? How the ? operator works:
Important limitation:
?The ? operator can only be used in functions returningResult(orOption). Since Rust 1.39,mainfunctions can also returnResult。
3.2 Using ? in main
The default main the function returns (); you cannot use ?. But you can make main Return Result:
Example
use
std
::
fs
::
File
;
use
std
::
io
::
{
self
,
Read
}
;
fn
read_file
(
path
:
&
str
)
->
Result
<
String
,
io::
Error
{
let
mut
content
=
String
::
new
(
)
;
File
::
open
(
path
)
?.read_to_string
(
&
mut
content
)
?
;
Ok
(
content
)
}
// main returns Result, so you can use ? in main
fn
main
(
)
->
Result
<
(
)
,
Box
<dyn std
::
error
::
Error
{
let
content
=
read_file
(
"hello.txt"
)
?
;
// ? works in main too
println
!
(
"{}"
,
content
)
;
Ok
(
(
)
)
}
4. Custom error types and categorized handling
In real projects, you usually need to handle different error types differently. Rust does this through the kind() method:
Example
use
std
::
fs
::
File
;
use
std
::
io
::
{
self
,
Read
}
;
// wrap file reading in a separate function and propagate errors with ?
fn
read_text_from_file
(
path
:
&
str
)
->
Result
<
String
,
io::
Error
{
let
mut
f
=
File
::
open
(
path
)
?
;
let
mut
s
=
String
::
new
(
)
;
f.read_to_string
(
&
mut
s
)
?
;
Ok
(
s
)
}
fn
main
(
)
{
match
read_text_from_file
(
"hello.txt"
)
{
Ok
(
content
)
=>
println
!
(
"File contents:\n{}"
,
content
)
,
Err
(
e
)
=>
{
// handle different error types differently
match
e.kind
(
)
{
io
::
ErrorKind
::
NotFound
=>
{
println
!
(
"File does not exist, please check the path"
)
;
}
io
::
ErrorKind
::
PermissionDenied
=>
{
println
!
(
"No permission to read this file"
)
;
}
_
=>
{
println
!
(
"An error occurred while reading the file: {}"
,
e
)
;
}
}
}
}
}
Result (when the file does not exist):
文件不存在,请检查路径
io::ErrorKind Common variants:
| ErrorKind | Meaning |
|---|---|
NotFound |
The file or directory does not exist |
PermissionDenied |
Insufficient permissions |
AlreadyExists |
File already exists (when creating) |
ConnectionRefused |
Connection Refused |
TimedOut |
Operation timed out |
InvalidInput |
Invalid argument |
5. Custom error types
In a project, you usually need to define your own error types to represent errors in business logic:
Example
use
std
::
fmt
;
use
std
::
num
::
ParseIntError
;
// define a custom error enum
[
derive
(
Debug
)
]
enum
AppError
{
IoError
(
std
::
io
::
Error
)
,
ParseError
(
ParseIntError
)
,
CustomError
(
String
)
,
}
// implement the Display trait for formatted output
impl
fmt
::
Display
for
AppError
{
fn
fmt
(
&
self
,
f
:
&
mut
fmt
::
Formatter
)
->
fmt
::
Result
{
match
self
{
AppError
::
IoError
(
e
)
=>
write
!
(
f
,
"IO error: {}"
,
e
)
,
AppError
::
ParseError
(
e
)
=>
write
!
(
f
,
"Parse error: {}"
,
e
)
,
AppError
::
CustomError
(
msg
)
=>
write
!
(
f
,
"Business error: {}"
,
msg
)
,
}
}
}
// implement the From trait so the ? operator converts error types automatically
impl
From
<
std
::
io
::
Error
for
AppError
{
fn
from
(
error
:
std
::
io
::
Error
)
->
Self
{
AppError
::
IoError
(
error
)
}
}
impl
From
<
ParseIntError
for
AppError
{
fn
from
(
error:
ParseIntError
)
->
Self
{
AppError
::
ParseError
(
error
)
}
}
// now you can use ? to handle different error types in the same function
fn
process_config
(
path
:
&
str
)
->
Result
<
i32
,
AppError
{
let
content
=
std::
fs
::
read_to_string
(
path
)
?
;
// io::Error → AppError
let
value
:
i32
=
content.trim
(
)
.parse
(
)
?
;
// ParseIntError → AppError
if
value
<
0
{
return
Err
(
AppError::
CustomError
(
"Configuration value cannot be negative"
.into
(
)
)
)
;
}
Ok
(
value
)
}
fn
main
(
)
{
match
process_config
(
"config.txt"
)
{
Ok
(
val
)
=>
println
!
(
"Configuration value: {}"
,
val
)
,
Err
(
e
)
=>
println
!
(
"Error: {}"
,
e
)
,
}
}
Third-party library recommendations:In real projects, you can use the
thiserrorlibrary to automatically derive theDisplayandFromimplementation, greatly reducing boilerplate code. For application-level code,anyhowthe library provides a convenientanyhow::Resulttype, suitable for rapid development.
6. Option: a value may be absent
Besides Result, Rust has another important enum for handling the "possibly no value" case --Option:
enum Option {
Some(T), // 有值
None, // 没有值
}
Option used to replace nullin other languages. Rust has no null, so any value that may be empty must be wrapped in Option Option:
Example
fn
find_user
(
id
:
u32
)
->
Option
<
String
{
match
id
{
1
=>
Some
(
"Alice"
.to_string
(
)
)
,
2
=>
Some
(
"Bob"
.to_string
(
)
)
,
_
=>
None
,// user does not exist
}
}
fn
main
(
)
{
// handle Option with match
match
find_user
(
1
)
{
Some
(
name
)
=>
println
!
(
"User found: {}"
,
name
)
,
None
=>
println
!
(
"User does not exist"
)
,
}
// simplify with if let
if
let
Some
(
name
)
=
find_user
(
99
)
{
println
!
(
"User found: {}"
,
name
)
;
}
else
{
println
!
(
"User does not exist"
)
;
}
// unwrap_or provides a default value
let
name
=
find_user
(
99
)
.unwrap_or
(
"Anonymous user"
.to_string
(
)
)
;
println
!
(
"Username: {}"
,
name
)
;
// anonymous user
// the ? operator also applies to Option
let
first_char
=
get_first_char
(
"hello"
)
;
println
!
(
"First character: {:?}"
,
first_char
)
;
// Some('h')
}
fn
get_first_char
(
s
:
&
str
)
->
Option
<
char
{
s.chars
(
)
.next
(
)// returns Option
}
Option The difference between Result comparison:
| Comparison Item | Option |
Result |
|---|---|---|
| Purpose | A value may be present or absent | An operation may succeed or fail |
| Success | Some(T) |
Ok(T) |
| Failure | None(no extra information) |
Err(E)(contains the error reason) |
| Typical scenario | lookups, optional fields, default values | file operations, network requests, parsing |
| Transform | ok_or(err) → Result |
ok() → Option |
Summary
| Scenario | Recommended approach | Description |
|---|---|---|
| the program encounters an unfixable bug | panic!("原因") |
terminates the program, for situations that should never happen |
| An operation may fail | Return Result |
forces the caller to handle the error |
| propagates the error within a function | ? operator |
automatically returns Err on failure and extracts the value on success |
| rapid prototyping / testing | .expect("原因") |
panics on failure, but with a clear error message |
| A value may be absent | Option |
Using Some / None replaces null |
| handle different error types separately | e.kind() |
match specific error variants |
| Custom error types | Create a class that implements Display + From |
together with ? implement automatic conversion |
Rust's error-handling philosophy:Errors are part of the type system, not exceptions to control flow. The compiler forces you to handle every possible error case, which makes your program more reliable at runtime.