Comparing Exceptions and Errors

kdevel kdevel at vogtner.de
Sun Jun 12 20:44:39 UTC 2022


On Sunday, 5 June 2022 at 23:57:19 UTC, Steven Schveighoffer 
wrote:
> On 6/5/22 6:09 PM, kdevel wrote:
>> On Sunday, 5 June 2022 at 20:53:32 UTC, Steven Schveighoffer 
>> wrote:
>> [...]
>>>> For this purpose nobody needs a separate subclass named 
>>>> `Error`. That works with `Exception`s.
>>>
>>> You can use Exceptions instead. But the difference is they 
>>> are part of the program instead of considered a check on the 
>>> program itself.
>> 
>> I have no clue what that means.
>
> An assert (or thrown error) is not ever supposed to happen, so 
> it's not part of the program. It's a check to ensure that the 
> program is sound and valid. You can feel free to insert as many 
> asserts as you want, and it should not be considered part of 
> the program.
>
> It basically says "If this condition is false, this entire 
> program is invalid, and I don't know how to continue from here."

Who is the narrator here? It is the author of the function which 
contains the assert. But this is not necessarily the author of 
the code which calls this function. Why should the author of the 
function be allowed *to terminate the whole the program* (be it 
via assert or exit)?

>> [...]
>> My code does not throw `Error`s. It always throws `Exception`s.
>
> Then I guess you should just ignore Errors and let the runtime 
> handle them? I'm not sure why this discussion is happening.

Because phobos/runtime throw Errors?

>>> changing all range functions to use the `checkedPopFront` and 
>>> `checkedFront`, just to find the error. Instead of letting 
>>> the asserts do their job.
>> 
>> It is not clear to me, what you now complain about. You first 
>> criticized that in
>> 
>> ```
>> for(auto r = range; !r.empty; r.popFront) {
>>     auto elem = r.front;
>> }
>> ```
>> 
>> there is triple checking that r is not empty, namely in 
>> !r.empty, in r.front and in r.popFront. One check, !r.emtpy, 
>> will suffice. Hence one can safely use
>> 
>> ```
>> for(auto r = range; !r.empty; r.popFront_unchecked) {
>>     auto elem = r.front_unchecked;
>> }
>> ```
>
> You can do this, and then if it fails, you have to guess that 
> maybe you did something wrong, and start using the checked 
> versions.

What shall go wrong in this example? Of course the compiler might 
generate wrong code. But it is not the aim of putting enforce and 
asserts into program code to guard against the bugs in the 
compiler.




More information about the Digitalmars-d-learn mailing list