Skip to content

Instantly share code, notes, and snippets.

@shtsoft
Created March 16, 2023 16:55
Show Gist options
  • Save shtsoft/81520bb6b1c35e1bf497088438cd8cea to your computer and use it in GitHub Desktop.
Save shtsoft/81520bb6b1c35e1bf497088438cd8cea to your computer and use it in GitHub Desktop.
mod exception_handling {
pub trait Exception<B> {
fn raise<A, K>(self, v: (), k: K) -> B
where
K: FnOnce(A) -> B;
}
pub struct ExceptionDiv {}
impl Exception<()> for ExceptionDiv {
fn raise<A, K>(self, _: (), _: K)
where
K: FnOnce(A),
{
println!("Error: Division By Zero.");
}
}
pub fn div(a: usize, b: usize, exception_handler: impl Exception<()>) {
let continuation = |x| {
println!("Result: {x}");
};
if b == 0 {
exception_handler.raise((), continuation);
} else {
continuation(a / b);
}
}
}
use exception_handling::*;
fn main() {
div(5, 2, ExceptionDiv {});
div(5, 0, ExceptionDiv {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment