Catch exception from another module

#1

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.

0 Likes

#2

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

1 Like

#3

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.

0 Likes

#4

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.

4 Likes