Assert and the optional Message

Regan Heath regan at netmail.co.nz
Fri Mar 9 04:05:20 PST 2012


On Fri, 09 Mar 2012 11:12:44 -0000, Jonathan M Davis <jmdavisProg at gmx.com>  
wrote:
> On Friday, March 09, 2012 11:03:38 Regan Heath wrote:
>> On Fri, 09 Mar 2012 08:20:33 -0000, Chris Pons <cmpons at gmail.com> wrote:
>> > Any idea why, system("PAUSE") does work?
>>
>> As Jonathan says, assert throws AssertError... which means, if you  
>> wanted
>> to you could catch it, for example...
>>
>> module asserting;
>>
>> import std.stdio;
>> import core.exception;
>>
>> debug
>> {
>>      import std.c.windows.windows;
>>      extern (C) int kbhit();
>> }
>>
>> void main()
>> {
>>      try
>>      {
>>          assert(false, "testing assert");
>>      }
>>      catch(AssertError e)
>>      {
>>          debug
>>          {
>>              writefln("Assertion failed: %s", e);
>>              writefln("Press any key to exit...");
>>              while(!kbhit())
>>                  Sleep(1);
>>          }
>>          throw e;
>>      }
>> }
>>
>> So, for debug builds your exe will output the assertion manually, and  
>> wait
>> for a key press.  Then re-throw the assertion (resulting in the d  
>> runtime
>> outputting the assertion again).  In release, no pause.
>>
>> Note: kbhit and Sleep are windows specific (sleep would be the unix
>> equivalent, not sure on one for kbhit).
>
> Bet advised that catching anything not derived from Exception is  
> generally a
> _bad_ idea (most of which are derived from Error), and AssertError is  
> _not_
> derived from Exception but rather Error. AssertErrors are not guaranteed  
> to
> invoke finally blocks, scope statements, or destructors. Your program is  
> in an
> invalid state when you catch an Error. So, while it may work in this
> particular case, it is _not_ something that you should be doing in  
> general. By
> far the worst thing to do would be to catch an Error and then continue
> executing. Errors are _supposed_ to kill your program.

Sound advice :)

R

-- 
Using Opera's revolutionary email client: http://www.opera.com/mail/


More information about the Digitalmars-d-learn mailing list