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.
View all comments
Show parent comment
0
u/ApprehensivePipe1584 Oct 29 '26
Removing try catch is removing stuff. My other mechanisms are just things arisen from my features. Unions are really nice to have and also just create a way for error handling, same for tagged enums. Multi return is nice to have and so are tuples and they just create error handling mechanisms by existing.