r/Compilers • • 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.

7 Upvotes

27 comments sorted by

View all comments

2

u/rjmarten Oct 29 '26

What's the difference between multiple returns and tuple returns?

And why do you want both tagged unions and bare unions?

I don't know if I can answer your question before knowing the vision behind all these features.

2

u/nculwell Oct 29 '26

Generally speaking, the difference between multiple returns and tuples is that tuples are a first-class object that you can pass around anywhere, whereas multiple returns are a special thing that only happens when functions return.

1

u/ApprehensivePipe1584 Oct 29 '26

Well Tuples can be used on their own and extract specific values, and multiple returns are... just multiple returns, andf must extract every value, like this:

(int, int) x = (123, 321); // a normal tuple
int x, int y = myMultiReturnFunction();
x = myFunctionThatRetunsATuple();
Tuples are their own datatype, multireturns are actual multiple-value-returns.
I have tagged unions as the easier prefered mechanism, but they are a runtime cost in both extraction and size, meanwhile raw C-Style unions allow for C interop, translation, direct layout instead of an additional 4+bytes for a integer tag, no type discerning, and it gives you control, a core goal of my language.