Last active
May 6, 2023 22:11
-
-
Save SpaceMonkeyForever/02d8fb2b5a64999f8a2ba8cb945d1ce9 to your computer and use it in GitHub Desktop.
Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
macro_rules! try_catch { | |
($try_block:expr, $catch_block:expr) => { | |
match (|| { | |
$try_block | |
Ok::<(), Box<dyn std::error::Error>>(()) | |
})() { | |
Ok(_) => {} | |
Err(e) => $catch_block(e), | |
} | |
}; | |
} | |
fn do_something() -> Result<(), &'static str> { | |
return Err("An error occurred"); | |
} | |
fn main() { | |
try_catch!( | |
{ | |
do_something()?; | |
println!("Operation succeeded"); | |
}, | |
|e| { | |
println!("Error: {}", e); | |
} | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
not recommended