Abhilash Gopalakrishna
Abhilash Gopalakrishna

Reputation: 980

Handling panics of external libraries

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:

Upvotes: 9

Views: 3377

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382177

DON'T PANIC

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

  • most often a bug, usually temporary because you've put an unwrap in your first prototyping
  • or a very extraordinary condition

As 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

Related Questions