assert unittest doesn't respect assertThrown

Brother Bill brotherbill at mail.com
Tue Jan 20 23:04:25 UTC 2026


On Tuesday, 20 January 2026 at 21:58:46 UTC, Ali Çehreli wrote:
> On 1/20/26 12:42 PM, Brother Bill wrote:
> > In a unittest, we have assertThrown average([1], [1, 2]));
> > As assert statement throws an exception.
>
> Yes, throws an exception but not Exception.
>
> > But the unittest fails, which seems odd, as an assert did thr
> > Have I found another bug in DMD?
>
> I happen to have DMD64 D Compiler v2.109.1 on this environment. 
> Your unittest passes.
>
> What fails is the code inside 'main'.
>
> > ```
> > import std.stdio : writeln;
> > import std.exception : enforce, assertThrown, assertNotThrown;
> >
> > void main()
> > {
> >      auto result = average([], []);
> >
> >      // assert is not caught in catch block
> >      // enforce is caught in catch block
> >      try
> >      {
> >          result = average([1], [1, 2]);
> >      }
> >      catch (Exception e)
> >      {
> >          writeln("Caught exception: ", e.msg);
> >      }
> > }
>
> There is the issue: The exception type that assert throws is 
> *not* under the Exception hierarchy but under the Error 
> hierarchy:
>
>  ```
>             Throwable (not recommended to catch)
>              ↗   ↖
>     Exception     Error (not recommended to catch)
>      ↗    ↖        ↗    ↖
>    ...     ...    ...      ...
> ```
>
> You could catch Throwable or Error. However, as they are not 
> recommended to be caught, perhaps a better option is to change 
> assert() to enforce(). enforce() throws a type under the 
> Exception hierarchy.
>
> Ali

Just curious as to why the unittest failed.  After all, the 
assert was thrown.
Is it because the try - catch block has an assert, but the catch 
block didn't catch it, which crashed the program before the 
unittest completed?


More information about the Digitalmars-d-learn mailing list