Skip to content

Commit

Permalink
Add panic docs
Browse files Browse the repository at this point in the history
  • Loading branch information
HKalbasi committed Sep 23, 2023
1 parent f6abf16 commit 0af87a2
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions book/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
- [Wellknown traits](./call_rust_from_cpp/wellknown_traits.md)
- [Layout policy](./call_rust_from_cpp/layout_policy.md)
- [Types with special support](./call_rust_from_cpp/special_types.md)
- [Panic and exceptions](./call_rust_from_cpp/panic_and_exceptions.md)
- [Calling C++ from Rust](./call_cpp_from_rust/index.md)
- [Calling C++ free functions](./call_cpp_from_rust/function.md)
- [Adding methods to Rust types](./call_cpp_from_rust/rust_impl.md)
Expand Down
37 changes: 37 additions & 0 deletions book/src/call_rust_from_cpp/panic_and_exceptions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Panic and exceptions

By default, Zngur aborts the process if an unwinding (Rust panic or C++ exception) reaches the cross language boundary. Handling
unwinding adds a non zero performance cost to every function call, and complicates things as catching an unwinding can result
in a corrupt state for some objects. (See [unwind safety](https://doc.rust-lang.org/std/panic/trait.UnwindSafe.html))

But Zngur has support for converting Rust panics into a C++ exception. To enable that, add

```
#convert_panic_to_exception
```

to your `main.zng` file. Now you can catch exceptions of kind `rust::Panic` for handling Rust panics:

```C++
try {
std::cout << "s[2] = " << *s.get(2).unwrap() << std::endl;
std::cout << "s[4] = " << *s.get(4).unwrap() << std::endl;
} catch (rust::Panic e) {
std::cout << "Rust panic happened" << std::endl;
}
```

assuming `s` contains `[2, 5, 7, 3]`, the above code prints:

```
s[2] = 7
thread '<unnamed>' panicked at 'called `Option::unwrap()` on a `None` value', examples/simple/src/generated.rs:184:39
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
s[4] = Rust panic happened
```

To disable the the log, you need to register a panic hook in the Rust side (See [this stack overflow question](https://stackoverflow.com/questions/35559267/suppress-panic-output-in-rust-when-using-paniccatch-unwind)). Note that
the `rust::Panic` object contains nothing, and you will lose the panic message.

For proper error handling, consider returning `Result` from your Rust functions, and throw native C++ exceptions with proper details in case of `Err` variant. Use
this panic to exception mechanism only in places which you need `catch_unwind` in Rust (e.g. for increasing fault tolerance).

0 comments on commit 0af87a2

Please sign in to comment.