[OT] Is there a real alternative to exceptions ?

Ali Çehreli acehreli at yahoo.com
Fri Feb 7 23:13:30 UTC 2025


On 2/6/25 6:02 PM, Manu wrote:

 > CppCon 2018: Brand & Nash “What Could Possibly Go Wrong?: A Tale of
 > Expectations and Exceptions” 
<https://www.youtube.com/watch?v=GC4cp4U2f2E>

Thanks for the link.

Going off topic to C++ land, for what it's worth, I've achieved 
something very similar with a couple of types and a couple of macros for 
C++. Yes, it's noisier than a proper language solution, but it just 
works helpfully. :)

(After watching that video, I thought I should have called my TRY macro 
DO because despite the name of mine, TRY does not throw but returns 
early upon failure.)

ReturnValue<int> foo(int i) {
   ENFORCE(i > 42,
           MSG("Invalid value: %d", i));
           //   \__ snprintf format string and arguments

   TRY(bar(i),
       MSG("Failed to do blah blah."));

   auto z = zar();
   // Must check here; otherwise, will assert(false) when using 'z'
   CHECK(z);

   // ... Use 'z' here as its implicit type e.g. 'float' if
   // it was ReturnValue<float>.

   return 666;    // Implicit successful ReturnValue<int>.
}

The MSG macro creates a lambda that is executed upon failure of ENFORCE, 
TRY, etc.

The error messages are created with snprintf, which is great when 
writing to a fixed-size error string buffer and when that buffer's free 
space is not sufficient. My error string buffer is a no-fail buffer that 
turns effectively into a C string array (plus length). That array is 
returned to the library caller so that they can print a backtrace of 
failure messages.

The size of my current buffer is just 4K and it works because most calls 
in my library are at most 5-6 level deep.

Every failure automatically returns to the calling function after 
inserting an error message to that error string array. This generates a 
backtrace of error messages.

One benefit of the macro system is that for the development build, all 
message generation lambdas are executed even for the successful cases. 
Such (non-)error messages are stored inside a huge buffer and later 
dumped to a file so that the developers can examine all error messages 
that would have been generated in the unhappy path in the actual 
product. (A summary of unique messages are brought to the top of the 
file.) This is both to make sure all messages make sense (e.g. not a 
pointer value but its content is printed) and that the generation of 
each error message will not crash the program. And of course, compiler 
warnings help with incorrect snprintf format strings as well.

Ali



More information about the Digitalmars-d mailing list