Basics

Rust panic

Handling Panics

Rust panic handles unrecoverable errors with panic! macro.

What is panic! in Rust?

In Rust, panic! is a macro that handles situations where the program encounters an unrecoverable error. When a panic! occurs, the program will terminate abruptly, providing a message about the error. This is useful for debugging and ensuring that errors are caught during development.

When to Use panic!

The panic! macro is generally used in situations where the program cannot continue executing safely. Common scenarios include:

  • Indexing out of bounds in an array or vector.
  • Attempting to unwrap a None value from an Option.
  • Violations of invariants that should never occur.

Basic Usage of panic!

To use the panic! macro, simply call it within your code with an optional error message. Here is a basic example:

panic! with Error Messages

Providing an error message with the panic! macro helps clarify why the program is terminating. You can include formatted strings to provide more detailed information:

Recovering from panic!

By default, when a panic! occurs, the program will unwind the stack, cleaning up resources. However, you can change this behavior by setting the panic strategy to abort in your Cargo.toml file, which will terminate the program immediately without unwinding. While recovering from a panic! is not possible, you can prevent certain panics by using error handling techniques like Result and Option.

Example: Using panic! in a Function

Let's see how panic! can be used within a function to halt execution when a function receives an invalid argument:

Conclusion

The panic! macro is a powerful tool in Rust for handling unrecoverable errors by terminating the program with a helpful error message. It should be used judiciously, primarily during development, to ensure that your code is robust and free from critical errors. Always consider handling errors gracefully, when possible, using Rust's Result and Option types.

Previous
fmt