Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Rust Error Handling


Share

Error Handling

In the previous chapter, a panic stopped the whole program. But many errors are expected, and the program should be able to continue. For example, a user can type "hello" where the program expects a number.

For errors like this, Rust uses an enum called Result. It works like Option, but instead of Some and None, it has these two variants:

  • Ok(value) - it worked, and here is the value
  • Err(error) - something went wrong, and here is the error

For example, the parse() method turns text into a number. parse::<i32>() means "turn this text into an i32". It returns a Result, because the text might not be a number:

Example

let good = "42".parse::<i32>();
let bad = "hello".parse::<i32>();

println!("{:?}", good); // Ok(42)
println!("{:?}", bad); // Err(ParseIntError { kind: InvalidDigit })
Try it Yourself »

"42" can be turned into a number, so the result is Ok(42). "hello" cannot, so the result is an Err, which tells you why: the text has an invalid digit.


Check the Result With match

Just like with Option, you can use match to handle both cases:

Example

let text = "abc";

match text.parse::<i32>() {
  Ok(number) => println!("The number is {}", number),
  Err(e) => println!("Error: {}", e),
}
Try it Yourself »

The text "abc" is not a number, so the Err branch runs and prints the error message: invalid digit found in string. The program does not crash. It continues after the match.


Return a Result From a Function

Your own functions can also return a Result. In Result<i32, String>, i32 is the type of the value when it works (Ok), and String is the type of the error (Err):

Example

fn buy(coins: i32, price: i32) -> Result<i32, String> {
  if price > coins {
    Err(String::from("Not enough coins"))
  } else {
    Ok(coins - price)
  }
}

fn main() {
  match buy(100, 30) {
    Ok(left) => println!("You bought it! Coins left: {}", left),
    Err(e) => println!("Error: {}", e),
  }

  match buy(20, 30) {
    Ok(left) => println!("You bought it! Coins left: {}", left),
    Err(e) => println!("Error: {}", e),
  }
}
Try it Yourself »

With 100 coins, you can buy an item that costs 30, so the function returns Ok(70). With only 20 coins, it returns an Err with the message "Not enough coins".



Use a Default Value

Like with Option, you can use unwrap_or() to get the value, or a default value if there is an error:

Example

let a = "42".parse::<i32>().unwrap_or(0);
let b = "hello".parse::<i32>().unwrap_or(0);

println!("a = {}", a); // 42
println!("b = {}", b); // 0
Try it Yourself »

unwrap() and expect()

The unwrap() method gives you the value inside Ok directly:

Example

let number = "42".parse::<i32>().unwrap();
println!("{}", number + 1); // 43
Try it Yourself »

But if the result is an Err, unwrap() panics and stops the program:

Example

let number = "hello".parse::<i32>().unwrap(); // Error
println!("{}", number + 1);
Try it Yourself »

The expect() method works the same way, but lets you write your own error message. This makes it easier to find out what went wrong:

Example

let number = "hello".parse::<i32>().expect("The text must be a whole number");
println!("{}", number + 1);
Try it Yourself »

Note: Only use unwrap() and expect() when you are sure that there is no error, or in small test programs. In other cases, handle the error with match or unwrap_or().


The ? Operator

When a function calls other functions that return a Result, checking each result with match can make the code long. The ? operator is a shortcut:

  • If the result is Ok, ? gives you the value inside, and the code continues
  • If the result is Err, ? stops the function right away, and returns the error

Example

use std::num::ParseIntError;

fn add_numbers(a: &str, b: &str) -> Result<i32, ParseIntError> {
  let x = a.parse::<i32>()?;
  let y = b.parse::<i32>()?;
  Ok(x + y)
}

fn main() {
  println!("{:?}", add_numbers("10", "20"));
  println!("{:?}", add_numbers("10", "abc"));
}
Try it Yourself »

ParseIntError is the error type that parse() returns when the text is not a whole number. It is imported with use at the top, just like HashMap.

In the second call, "abc" cannot be turned into a number, so ? returns the error, and Ok(x + y) is never reached.

Note: You can only use ? inside a function that returns a Result (or an Option).


Summary

Code What it does
match Handles Ok and Err in different ways
unwrap_or(value) Gives the value, or a default value if there is an error
? Gives the value, or returns the error from the function
unwrap() and expect() Gives the value, but panics if there is an error


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.