Catch exception from another module


How I can catch exception from another module?
For example, I have two modules: A and B. Code in B not controlled by me, but A uses B. How I can protect A from panics, throwed by B? For example, if B made division by zero, it panics, and I cannot catch this panics.



panics are not supposed to be caught, but if you really need to, you can use std::panic::catch_unwind

1 Like


Easy! There are no exceptions in Rust. Problem solved! (*scnr*)

Panics are not meant for “catching”. Only panic, when you can’t do anything else, elsewise return a Result or Option.



In Rust, panics are for bugs. B is not supposed to have a bug that causes division by zero. It should use .checked_div() for example.

Rust has panic = abort setting, so it’s possible that any panic anywhere will immediately abort the entire program with absolutely no way to prevent this.

“Exceptions” in Rust are done with the Result type and the ? (try) operator.