Rust Panic Handling Example

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we learn about the error handling mechanism panic in Rust. It is a simple mechanism that prints an error message, unwinds the stack, and usually exits the program. The lab provides an example where panic is explicitly called when the beverage is "lemonade".

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/MemorySafetyandManagementGroup(["`Memory Safety and Management`"]) rust(("`Rust`")) -.-> rust/ErrorHandlingandDebuggingGroup(["`Error Handling and Debugging`"]) rust/DataTypesGroup -.-> rust/string_type("`String Type`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("`Lifetime Specifiers`") rust/ErrorHandlingandDebuggingGroup -.-> rust/panic_usage("`panic! Usage`") subgraph Lab Skills rust/string_type -.-> lab-99231{{"`Rust Panic Handling Example`"}} rust/function_syntax -.-> lab-99231{{"`Rust Panic Handling Example`"}} rust/expressions_statements -.-> lab-99231{{"`Rust Panic Handling Example`"}} rust/lifetime_specifiers -.-> lab-99231{{"`Rust Panic Handling Example`"}} rust/panic_usage -.-> lab-99231{{"`Rust Panic Handling Example`"}} end

panic

The simplest error handling mechanism we will see is panic. It prints an error message, starts unwinding the stack, and usually exits the program. Here, we explicitly call panic on our error condition:

fn drink(beverage: &str) {
    // You shouldn't drink too much sugary beverages.
    if beverage == "lemonade" { panic!("AAAaaaaa!!!!"); }

    println!("Some refreshing {} is all I need.", beverage);
}

fn main() {
    drink("water");
    drink("lemonade");
}

Summary

Congratulations! You have completed the Panic lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like