[Issue 4644] assertExceptionThrown to assert that a particular exception was thrown

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sun Aug 15 14:34:24 PDT 2010


http://d.puremagic.com/issues/show_bug.cgi?id=4644



--- Comment #4 from Andrej Mitrovic <andrej.mitrovich at gmail.com> 2010-08-15 14:34:21 PDT ---
There we go, this should now work:


import std.stream, std.stdio;

void assertExceptionThrown(alias func, alias exc, T...)(T args)
{
    auto funcName = __traits(identifier, func);

    try
    {
        func(args);
    }
    catch (exc e)
    {
        return;     // Expected exception was thrown
    }
    catch (Exception e)
    {
        writeln(e);
    }

    writefln("Error: Call to %s did not throw %s", funcName, typeid(exc));
    assert(0);
}

unittest
{
    assertExceptionThrown!(willThrow, core.exception.AssertError)(4);
}

void willThrow(int i)
{
    //~ assert(0);
    //~ throw new SeekException("Oops a file exploded!");
}

void main()
{
}


So, if you leave it like this it will complain about the expected exception not
being thrown. 

If you uncomment the first line, it will run silently and return. 

I did add another gerenal Exception handler in the templated function, so when
a completely different exception is thrown (in this case just uncomment the
second line here) you will still be notified that the *expected* exception did
not throw even though another one did.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list