How to enable feedback for AssertError?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jun 5 17:09:15 PDT 2016


On 06/05/2016 07:39 AM, your_name wrote:

 > The problem I have is whenever an assert in my debug build fails the
 > program or thread is just killed silently.

That's strange. When an assertion fails, the stack trace is printed and 
the program is terminated. For example:

void fun(int i) {
     assert(i == 7);
}

void main() {
     fun(42);
}

That program fails loudly :) with something similar to the following:

core.exception.AssertError at deneme.d(2): Assertion failure
----------------
??:? _d_assert [0x422b9b]
??:? void deneme.__assert(int) [0x422acc]
??:? void deneme.fun(int) [0x422a62]
??:? _Dmain [0x422a75]
??:? _D2rt6dmain211_d_run_mainUiPPaPUAAaZiZ6runAllMFZ9__lambda1MFZv 
[0x423012]
??:? void rt.dmain2._d_run_main(int, char**, extern (C) int 
function(char[][])*).tryExec(scope void delegate()) [0x422f5c]
??:? void rt.dmain2._d_run_main(int, char**, extern (C) int 
function(char[][])*).runAll() [0x422fce]
??:? void rt.dmain2._d_run_main(int, char**, extern (C) int 
function(char[][])*).tryExec(scope void delegate()) [0x422f5c]
??:? _d_run_main [0x422ecd]
??:? main [0x422b05]
??:? __libc_start_main [0x30ea082f]

If you want to prevent termination, it is possible but not recommended 
to catch and swallow AssertError (or Error, or Throwable):

import core.exception;

void fun(int i) {
     assert(i == 7);
}

void main() {
     try {
         fun(42);

     } catch (AssertError) {
         // Something bad happened. We can't trust the state
         // of this program any more.
     }
}

As noted, when an Error is thrown, you can't know whether the program 
can do anything correctly any more.

Ali



More information about the Digitalmars-d-learn mailing list