What should happen when the assert message expression throws?

kdevel kdevel at vogtner.de
Sun Nov 27 22:35:40 UTC 2022


On Saturday, 26 November 2022 at 12:32:40 UTC, Ali Çehreli wrote:
> On 11/25/22 08:48, kdevel wrote:
>
>> I would like to know if there is a representation of that 
>> ominous
>> "invalid state" in terms of bits and bytes. Well, it doesn't 
>> have to.
>> But if we are talking about "invalid state" we should be able 
>> to explain
>> what we mean when we use that group of words. I don't use the 
>> term
>> because I do not intuitively know what it means and the D docs 
>> do not
>> define the term either.
>
> I think it is definition and comes from convention:
>
> - Errors represent situations where the program should not 
> continue

If the programmer who implements a function/method is not the 
author of `main` he most certainly is not in charge of deciding 
on the fate of the running program.

[...]

> - If configFile was a string input by the user, then the 
> following is appropriate:
>
>   enforce(exists(configFile), /* ... */)
> 
> - If configFile was a string representing a file e.g. that has 
> just been generated by the same program, then the following is 
> appropriate:
>
>   assert(exists(configFile), /* ... */)

That is a nice example! In both cases I would define an 
Exception-Class

    ConfigFileNotFound : Exception {
       ...
    }

and let enforce create and throw a corresponding object. For me, 
it makes no difference if the file name is user input, taken from 
the command line, or hardcoded into the program. Well, actually I 
would not code such a check at all. I would let the open function 
throw the exception (also to avoid TOCTTOU).

The decision if the program can continue without configuration 
file is probably taken in `main` or in the consumer of that 
configuration data: If there is a default configuration dataset 
the program might continue.

[...]

> Having said that, that assert means this to me: "For this 
> program to be able continue, the value of 'a' must be 0."

In order not to convey that meaning in real programms I only use 
asserts in unittests.

[...]

> I am repeating myself but I think your program has a programmer 
> error in that condition.

There really is none. The failure of the assert expression is on 
purpose.

> Swallowing the thrown AssertError is interesting but I don't 
> think that program has any invalid state.

Actually you do not extract that information from the code itself.

> The way I see it, valid state is defined by the collection of 
> assertion checks,

But sometimes you don't believe what the code says. If it does 
not match up with your presuppositions you testify validity 
though the assert checks fail. But then isn't that invalid state 
a non-local or even a subjective thing?




More information about the Digitalmars-d mailing list