Skip to content

Commit bd4719b

Browse files
committed
Add section about panicking.
1 parent da3b171 commit bd4719b

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
- [Links](./setup/links.md)
77
- [Hello World](./hello_world.md)
88
- [Delay](./delay.md)
9+
- [Panicking](./panicking.md)
910
- [Blinky](./blinky.md)
1011
- [Exercise: working with inputs](./button.md)
1112
- [Interrupts](./interrupt_intro.md)

src/panicking.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Panicking
2+
3+
When an unrecoverable error happens in Rust, the program panics.
4+
There are several ways that panics can be handled, but it usually ends up with your program exiting (crashing).
5+
6+
Let's try it. Add this before the "hello world" message:
7+
8+
```rust
9+
panic!("Oh no!");
10+
```
11+
12+
We should observe two things:
13+
14+
1. Compiler gives us "unreachable statement" warning for the code after `panic!()`.
15+
2. When we run our program, it doesn't appear to do anything.
16+
17+
Let's fix point 2 by displaying the panic information. First, let's import `error` macro from the `log` crate:
18+
19+
```rust
20+
use log::{info, error};
21+
```
22+
23+
Then, modify the panic handler, located just after import statements, like so:
24+
25+
1. Give a name to the `PanicInfo` variable. In Rust, we use `_` when we have unused variables that we don't want to name.
26+
2. Print the panic info using the `error!()` macro.
27+
28+
```rust
29+
#[panic_handler]
30+
fn panic(panic_info: &core::panic::PanicInfo) -> ! {
31+
error!("{panic_info}");
32+
loop {}
33+
}
34+
```
35+
36+
Now, we get a useful message about why our program crashed:
37+
38+
```
39+
ERROR - panicked at src/bin/main.rs:32:9:
40+
Oh no!
41+
```
42+
43+
Finally, don't forget to delete the `panic!()` call before proceeding to the next section!

0 commit comments

Comments
 (0)