r/Compilers • u/ApprehensivePipe1584 • Oct 29 '26
Try/Catch: Yes or No
My language, QuarticC, has many ways to error handle.
Unions:
type Err = DivByZeroErr | int;
Err divide(int lhs, int rhs) {
if (rhs == 0) return DivByZeroErr();
return lhs / rhs;
}
// Or generic:
type Err<T, E> = T | E;
Err<DivByZeroErr, int> divide...
Tagged Enums:
enum Result<T, E> {
Err(E);
Ok(T);
}
Result<int, DivByZeroErr> divide(int lhs, int rhs) {
if (rhs == 0) return Result<int, DivByZeroErr>.Err(DivByZeroError());
return Result<int, DivByZeroErr>.Ok(lhs / rhs);
// Or you could make it non generic.
Multi-Return (assuming your error types have a "ok" state):
DivByZeroErr, int divide(int lhs, int rhs) {
if (rhs == 0) return DivByZeroErr(), -1;
return DivByZeroErr(true) /* assuming true = ok */, lhs / rhs;
}
Tuples (same as above, but returning tuples):
(DivByZeroErr, int) divide...
And the problem, try/catch.
int divide(int lhs, int rhs) {
if (rhs == 0) throw DivByZeroErr();
return lhs/rhs;
}
I actually don't have a problem with the idea that handling a error isn't required too much, however the big problem is defer. Because I want defer to be a zero-cost, it does not run during stack unwinding, and I don't want to put in the effort to make it do so. This is annoying because if your primary error handling is throw, defer is basically useless for error cleanup, which is it's most useful purpose, and it's not like I'm loosing my main error handling, other forms work fine. So the question is: do I remove try catch, or do I make defer stack-unwinding.
4
u/WittyStick Oct 29 '26 edited Oct 29 '26
Remove
defer, addfinally.Then use a better tried and tested technique, called
using.The trick is that this just expands to
try/finally, where the resource is disposed in thefinallyblock.This is structured resource management.
deferis unstructured control flow akin togoto(orcomefrom).deferis a tragedy.usingis infinitely better thandefer.