The solution to "Error handling"...

Walter Bright newshound2 at digitalmars.com
Wed Jul 8 07:11:40 UTC 2026


On 7/6/2026 5:00 AM, Dennis wrote:
> In D, you can always check `array.length`. It's designed so that whenever 
> `array.ptr` is null, `array.length` is also 0 (save for `@system` shenanigans), 
> defining the null error out of existence even when the variable is 
> 0-initialized. I love that design!

Yes, that worked out nicely!

>> What if he wrote a text editing program that uses this philosophy? When the 
>> user wants to save their work, and fopen returns such a "nil struct" instead 
>> of a null pointer, it would appear to the user that their file was saved to 
>> disk, only for it to be completely lost once the program exits.

One solution is for the nil struct to log errors internally, then at an 
appropriate time the errors can be examined and transmitted to the user.

> Defining errors out of existence is a hard sell, because it's not a single 
> pattern that you universally apply. It's a case-by-case thing that requires real 
> context and critical evaluation of your entire stack.

There may be a general way of doing it, but I am not experienced enough in it to 
see it. I agree it's a case by case thing.

In the D compiler, the error message printer keeps a sticky flag that there were 
errors. It also uses "error nodes" (like the nil struct) that enable the 
compiler to continue gracefully. The error recovery of the compiler got a great 
deal better when that was adopted. (The earlier scheme was an attempt to 
"repair" the bad input, which never worked very well.)

In any case, it's a fun thing to think about with your own code.



More information about the Digitalmars-d mailing list