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
3
u/WittyStick Oct 29 '26
You don't actually need
finallyif you remove all unstructured control flow so that nothing can accidentally cause whatever is inusingto leak.Eg, you can use this trick in C:
Usage:
This works because the
forloop only runs once, so the secondary block of theusingis actually just a secondary block in a run-only-once for loop (which the compiler can detect and optimize it away).However, the caveat to this approach is unstructured control flow:
goto,break,continue,return- if you use these inside the secondary block then the resource may not be released. This is something that you can trivially fix if you control the language though - you can just restrict unstructured control flow from being used in such context.Structured resource handling (
using) is better than unstructured resource handling (viadefer).Just like structured looping (
for/while) is better than unstructured looping (viagoto).