Alternatives to exceptions for error handling
Jacob Carlborg
doob at me.com
Sun Nov 29 19:52:27 UTC 2020
On 2020-11-29 19:17, Roman Kashitsyn wrote:
> It's mostly the question of values: writing nice looking code quickly vs
> writing code that handles all the edge cases thoroughly. It's much more
> fun to write the first kind of code and it's perfectly justified in many
> cases. Though as a user (of an app or a library) you would probably
> prefer the second kind of code.
>
> Thoughtful error handling never looks good, and exceptions don't help
> with that at all: try/catch syntax is very heavyweight and encourages
> you to propagate errors instead of dealing with them where they arise.
In many cases you don't know what to do with an error so you need to
propagate it up the stack. For example, opening a file. If that fails,
the function has no idea if that's a critical error or not. It might be
a config file that is missing and the application cannot start without
it. Or it might the that a user selected a file which it doesn't have
permission to open.
> Exceptions also make type signatures less precise: it's hard to be sure
> I handled all the errors I can recover from if I don't know which errors
> can actually occur. There is no way to tell without inspecting the full
> transitive closure of the code I call into.
>
> So it would be nice to have an alternative to exceptions even if it's
> not going to be the default mechanism.
>
> Herb Sutter's proposal looks OK but it doesn't solve most of the
> problems I have with exceptions:
> 1. The syntax for propagating errors is OK, but the syntax for
> *handling* them is still heavyweight.
> 2. All the error types are mashed into std::error, so I still don't
> know which errors are possible at each call.
I have some ideas that I think solve most of these problems. With a
syntax that (hopefully) won't alienate users. Perhaps I should write
those down.
--
/Jacob Carlborg
More information about the Digitalmars-d
mailing list