What should happen when the assert message expression throws?

kdevel kdevel at vogtner.de
Fri Dec 9 14:36:04 UTC 2022


On Thursday, 8 December 2022 at 16:02:14 UTC, H. S. Teoh wrote:

[...]

> Yeah, for checking the existence of a file I'd use enforce, not 
> assert.

You would write

    enforce (exists (filename));
    auto text = readText (filename);

instead of simply

    auto text = readText (filename);  // (1)

? I mean isn't the enforce redundant and also prone to TOCTTOU?

> Assert is for catching logic errors in the program; a missing 
> file in the filesystem isn't a logic error,

Logic error means that a program does not implement the 
specification.
Example: The program should read the config file "config.cfg" 
which is
misspelled as in

    enum config_filename = "config.cgf";
    auto config = readText (config_filename);

When the program is started a FileException is thrown. Nobody is 
forced
to catch logic errors with asserts.

Now: A file system is essentially a key/value store. (1) can also 
be
written as

    auto value = readText (key);

With a nicer notation this becomes

    auto value = obj [key]; // (2)

where obj is an instance of some Filesystem class. IMNSHO it is 
hard
to explain, why in case of

    string[string] obj;
    string key;

or

    string [] obj;
    int key;

the expression (2) throws an Error (capital E) while in the case 
of

    Filesystem obj;
    string key;

it throws an Exception.


More information about the Digitalmars-d mailing list