r/transprogrammer • u/definitelynotagirl99 • Jul 20 '24
Implementing exceptions
Just wanna know if anyone knows a more time-efficient way of implementing exceptions in a language than this or sees any issues with this design :3

handlethrow would exist separately for each try-catch clause
(obv this will only work for x86 but smth similar should work for all major architectures)
15
Upvotes
View all comments
Show parent comment
3
u/anydalch Jul 21 '24
Your other responder was talking briefly about Rust's
Result. The short version is that each function which can fail explicitly returnsenum { Ok(ReturnValue), Err(Error) }, and then the caller inspects the return value and handles appropriately. The compiler doesn't need to know about this at all, but e.g. Rust has syntactic sugar for "re-throwing" anErrresult.I mention it as similar because what happens is that every function which can fail encodes in its return value whether it succeeded or failed, and the error value it "throws" is a part of that return value. Each caller of a fallible function branches on whether the return value was success or failure, and handles them appropriately.
This technique is generally described differently from exceptions because it doesn't introduce any special control flow for unwinding, at least at the level of compiled code, it just uses normal calls and returns. But withoutboats has some blog posts which I'm too lazy to find about how Rust could have used a syntax which looks very much like traditional exceptions, they just chose not to.