Reputation: 980
I am new to Rust and have come to understand Rust defaults to panics and not exceptions.
I have a rust project that depends on external libraries.
I have handled all unwraps and ?
's in my code using match
statements, but I am not sure how to handle a panic
by external libraries.
In other languages I would just catch an exception thrown by the library.
As Rust defaults to panics, the libraries don't return an exception but panic
and thus abort execution of the thread.
I would ideally want to log and continue execution, not panic and abort.
I have tried the following:
catch_unwind
, but this looks like something I can't use on an external library.log-panics
crate, which logs the panic using a panic hook. I am able to log the panic, but not prevent aborts.Upvotes: 9
Views: 3377
Reputation: 382177
I mean, that's the real solution: you must avoid panics, not try to recover from them when they happen.
Some languages casually use exceptions to deal with conditions preventing some operations, and manage them without crashing. In Rust, those unsupported conditions are managed with errors, not panics.
A panic in Rust is
unwrap
in your first prototypingAs the Book says:
When code panics, there’s no way to recover
The various utilities like catch_unwind
are, at best, aiming at more gracefully quitting, they don't let your program run as if nobody happened.
When a crate you use panics, first check you're using the function as expected (and if you can't check that without panicking that's a bug in that lib), then either have it fixed or fix it yourself if you can.
There's no reasonable way to deal with a casual panic, apart from crashing as fast as possible. A panic isn't casual in the life of your program.
Upvotes: 15