Comparing Exceptions and Errors

kdevel kdevel at vogtner.de
Sat Jun 4 22:56:10 UTC 2022


On Saturday, 4 June 2022 at 16:55:31 UTC, Steven Schveighoffer 
wrote:
[...]
> The point of an `Error` is that your code can assume it cannot 
> happen. If it does happen, the code is invalid.

According to my favorite dictionary "assume" means "take for 
granted" [1]. If `Error`s may happen how can code (or its author) 
"assume" that `Error`s cannot happen?

That makes absolutely no sense to me.

> This is reflected in the fact that the compiler will omit 
> cleanup code if an `Error` is thrown (it can assume that it 
> will never happen).

But instead the compiler should *emit* the cleanup code and we 
would not have to discuss here carefully avoiding to name the 
root cause of all this entanglements.

> The point of using `Error` is for a last resort check for 
> program correctness (because you failed to validate the input 
> before getting to that point).

If the code threw an `Exception` instead of an `Error` everything 
would be fine.

>[...] I actually replaced some arrays with an
> `Exception` throwing wrapper because I didn't want to crash the 
> whole server for certain cases, and I didn't want to 
> continuously validate array indexes.

+1

> [...]
> A great example are range functions. Often times you see at the 
> beginning of any `popFront` method the statement 
> `assert(!empty);`. This is universally accepted, as you 
> shouldn't be calling `popFront` if you haven't checked for 
> `empty`.

Yep.

```
core.exception.AssertError@[...]linux/bin64/../../src/phobos/std/range/primitives.d(2280): Attempting to popFront() past the end of an array of int
```

I see no difference to the potentially invalid array index case. 
It would ease the use of the range if it threw an `Exception`.

[1] https://www.thefreedictionary.com/assume


More information about the Digitalmars-d-learn mailing list