Remix.run Logo
Cthulhu_ a day ago

What does make exceptions bad in my opinion (and shared by Go developers?) is a few things:

1. Exceptions are expensive (at least in Java / C#), as they generate a stack trace every time. Which is fine for actually exceptional situations, the equivalent of `panic()` in Go, but:

2. Exceptions are thrown for situations that are not exceptional, e.g. files that don't exist, database rows that don't exist, etc. Those are simple business logic cases. The workaround is defensive coding, check if the file exists first, check if the row exists? that kind of thing.

3. The inconsistency between checked and unchecked exceptions.

4. Distance - but this is developer / implementation specific - between calling a function that can throw an error and handling it.

But #2 is the big one I think. Go's error handling is one solution, but if it's about correct code, then more functional languages that use the Either pattern or whatever it's called formally are even better. Go's approach is the more / most pragmatic of the options.

cesarb a day ago | parent [-]

> e.g. files that don't exist, database rows that don't exist, etc. [...] The workaround is defensive coding, check if the file exists first, check if the row exists?

Ugh NO. Please don't. You should never "check if the file exists first". It can stop existing between your check and your later attempt at opening the file (the same with database rows). That can even lead to security issues. The name for that kind of programming mistake, as a vulnerability class, is TOCTOU (time-of-check to time-of-use).

The correct way is always to try to do the operation in a single step, and handle the "does not exist" error return, be it a traditional error return (negative result with errno as ENOENT), a sum type (either the result or an error), or an exception.

OtomotO a day ago | parent [-]

Totally agreed, but as the previous poster wrote:

an exception is meant for EXCEPTIONAL behavior.

So it may be that the file access throws an exception but generally, I wouldn't agree.