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 edited Oct 29 '26
I'm absolutely not removing defer. defer is a feature i am keeping as it allows so much code removal for early returns, breaks, etc, adding finally to try/catch is a pain and something i don't want to add, and goto isn't neccesarily bad. My language is not RAII, and doesn't really do that or automatic cleanup and thus using doesn't really fit my language. I probably will be removing try-catch.