[OT] - C++ exceptions are becoming more and more problematic

meta meta at gmail.com
Fri Feb 25 04:33:43 UTC 2022


> I've yet to see a convincing example of error handling based on 
> tagged unions / multiple returns / etc., that doesn't suffer 
> from the explicit handling problem I describe above.  If you 
> have one, please enlighten me.


```D
void parseData() {

     string content = null;

     try {
         content = readFile("poem.txt");
     }
     catch (IOException e) {
         return false;
     }

     if (content.length == 0)
         throw new Exception("No data");

     // parse
}



// either bubble up the exception or handle it
try
{
     parseData();
}
catch ()
{}

```

vs

```zig
fn parseData() !void {

     var content = try readFile("poem.txt") catch {
         // handle error
         IOError => {},
     };

     if (content.len == 0) return err.NoData


    // parse
}


// either bubble up the error or handle it
try parseData();

```

(I'm not sure if that is the right syntax, It's been a while I 
haven't looked at zig)

While the zig version is not perfect, it is nicer, no extra 
indentation for try/catch, you can bubble up the error just like 
with an Exception, you avoid the cost and inconvenience of using 
Exceptions!

It's explicit, and you get to choose if you want to handle them.. 
or not! but at some points you will have to! that's what I call a 
healthy way to manage a code base!

They use enum for errors, and you can extend them if I remember 
correctly

Having multiple return value would make it even better, I'm a fan 
of Go's way, despite what people said about it!


Plus, they are looking to improve it 
https://github.com/golang/go/wiki/Go2ErrorHandlingFeedback



More information about the Digitalmars-d mailing list