Skip to content

Instantly share code, notes, and snippets.

@shtsoft
Created March 16, 2023 16:55
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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