rust-lang / nomicon

The Dark Arts of Advanced and Unsafe Rust Programming
https://doc.rust-lang.org/nomicon/
Apache License 2.0
1.82k stars 263 forks source link

panic_handler isn't just for no_std applications #373

Open grahamc opened 2 years ago

grahamc commented 2 years ago

The documentation on https://doc.rust-lang.org/nomicon/panic-handler.html suggests that specifying panic handlers is just for no_std applications:

[panic_handler] is used to define the behavior of panic! in #![no_std] applications.

However it may also be used for other applications too, like this Play link:

https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn%20main()%20%7B%0Ause%20std%3A%3Apanic%3B%0A%0Apanic%3A%3Aset_hook(Box%3A%3Anew(%7Cpanic_info%7C%20%7B%0A%20%20%20%20if%20let%20Some(s)%20%3D%20panic_info.payload().downcast_ref%3A%3A%3C%26str%3E()%20%7B%0A%20%20%20%20%20%20%20%20println!(%22panic%20occurred%3A%20%7Bs%3A%3F%7D%22)%3B%0A%20%20%20%20%7D%20else%20%7B%0A%20%20%20%20%20%20%20%20println!(%22panic%20occurred%22)%3B%0A%20%20%20%20%7D%0A%7D))%3B%0A%0Apanic!(%22Normal%20panic%22)%3B%0A%7D&edition=2021

This was quite confusing for me because the nomicon was the first resource in DDG for "rust panic handler", which suggested that indeed I was wading into spooky waters:

image

I'm not sure the best way to rephrase it, but I think it shouldn't suggest that it is only for no_std.

ehuss commented 2 years ago

Maybe I'm a bit confused by where the concern is. Looking at your playground link, I don't see the use of #[panic_handler]. As mentioned, there must be only one #[panic_handler], and there is already one defined in the standard library. Thus, it is only relevant to define a #[panic_handler] in a no_std environment.

Perhaps it could be reworded to say:

The #[panic_handler] attribute is used to define the behavior of panic!. #[panic_handler] must be applied to a function with the signature fn(&PanicInfo) -> !. The core::panic::PanicInfo struct contains information about the location of the panic. There can be only one panic handler in the dependency graph of a binary / dylib / cdylib crate. Defining your own #[panic_handler] is only relevant for no_std development since std defines its own panic handler. If you need to customize panic behavior with a std application, then consider using std::panic::set_hook.

Does that help clarify?

grahamc commented 2 years ago

Dang, thanks! Double misunderstanding!