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

Dukc ajieskola at gmail.com
Fri Feb 25 08:01:15 UTC 2022


On Friday, 25 February 2022 at 00:30:49 UTC, H. S. Teoh wrote:
> For example, if you have function f that calls g and h, and g 
> and h have their own set of possible error enums, then what 
> should f return?  You either create yet another enum that 
> subsumes both (and the caller then has the hairy task of making 
> sense of which error codes comes from where and what to do with 
> it), or, if you have to do this for all 65,535 functions in 
> your entire codebase, just give up and go to a global binary 
> {ok, fail} enum. Or, to harken back to my C example, OK and 
> INTERNAL_ERR, which is where all return-code-based error 
> handling inevitably gravitates towards. Which is about as 
> useful as a BSOD every time the program encounters the 
> slightest difficulty.

You can also make your errors dynamically typed. Returning 
exceptions or strings would be ways to achieve this. That way, 
when handling errors, you handle errors you know. If it's some 
unknown exception or error code in a string, you simply return it 
and let the caller handle it. Same as with throwing exceptions, 
except it's manual.

You're right though that being manual is sometimes a downside. On 
the upside, you know when you're using a function that might 
error, because you have to write that error handling wrapper, so 
you don't just accidently propagate that error. But there's a 
temptation to just assert false on an error that could be handled 
or worse, pretend it didn't happen. Especially if you would have 
to change type of the function return to account for errors.

Same thing when reading error-handling code. On the other hand 
it's clutter that obfuscates what the code normally does, but at 
least you're not oblivious to the fact that there's potential for 
abnormal situations.

I suspect that an already written codebase is better off with 
returned error values, assuming they are implemented so that they 
cannot be implicitly discarded. But exceptions are still a good 
choice, because it's less work to implement error handling in the 
first place with them, than with error values.




More information about the Digitalmars-d mailing list