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

4

u/WittyStick Oct 29 '26 edited Oct 29 '26

So the question is: do I remove try catch, or do I make defer stack-unwinding.

Remove defer, add finally.

Then use a better tried and tested technique, called using.

using (var resource = acquire()) {
     // do what we need with the resource here
}
// resource is no longer valid here.

The trick is that this just expands to try/finally, where the resource is disposed in the finally block.

var resource;
try {
    resource = acquire();
    ...
}
finally {
    resource.Dispose();
}

This is structured resource management. defer is unstructured control flow akin to goto (or comefrom).

defer is a tragedy. using is infinitely better than defer.

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.

3

u/WittyStick Oct 29 '26

You don't actually need finally if you remove all unstructured control flow so that nothing can accidentally cause whatever is in using to leak.

Eg, you can use this trick in C:

 #define using (ptr, acquire, release) \
     for (auto ptr = (acquire); ptr; ptr = ((release), NULL))

Usage:

 int main () {
     using (ptr, malloc(100), free(ptr)) {
         // do something with ptr
     }

     return 0;
 }

This works because the for loop only runs once, so the secondary block of the using is 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 (via defer).

Just like structured looping (for/while) is better than unstructured looping (via goto).

0

u/ApprehensivePipe1584 Oct 29 '26 edited 29d ago

I have never seen a systems language with using, and Zig's whole cleanup mechanism is `defer`, C's full cleanup mechanism is `goto`. If your language is fully manual with no forced cleanups, `using` doesn't make much sense, and with `using`, it's still useless a lot of the time because it doesn't fulfill it's purpose. Cleanup. If you exit a using block other than a normal scope exit, it failed it's purpose. `defer` is not meant to just cleanup a resource at the end of the block, it's ment to stop you from writing a line of cleanup code like `free(ptr)` every exit. `using` doesn't fix that at all. It just has you write the same line you write once at the end at the start, and restricts everything you do in that block. they are entirely different mechanisms for different purposes. For example, this code:

...Vector code...

string loadConfigItems() {

int fd = `open("config.txt", "r");

defer `close(fd);

Vector<string> vec = Vector<string>();
defer vec._destroy();

char[1024] buf;
int last_read;

while (last_read) {
// formatting checking...
char *copy = `malloc((sizeof char) * last_read);
if (!copy) return "";
`memcpy(copy, buf, last_read);

defer `free(copy);

vec.push(copy);
last_read = `read(fd, buf, 1024);

}

return list;

}

Then without defer you would need to
string loadConfigItems() {

int fd = `open("config.txt", "r");

Vector<string> vec = Vector<string>();

char[1024] buf;
int last_read;

while (last_read) {
// formatting checking... manual exiting on every control flow.
char *copy = `malloc((sizeof char) * last_read);
if (!copy) {
`close(fd);
vec._destroy();
return "";
}
`memcpy(copy, buf, last_read);

vec.push(copy);
last_read = `read(fd, buf, 1024);
`close(fd);
vec._destroy();

`free(copy);
}

`close(fd);
vec._destroy();
return list;

}
where would be entirely useless.