assert unittest doesn't respect assertThrown
Brother Bill
brotherbill at mail.com
Tue Jan 20 22:51:35 UTC 2026
On Tuesday, 20 January 2026 at 21:58:46 UTC, Ali Çehreli wrote:
> 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
That is true. I got rid of the try catch, with only the try
body, and the unittest passes.
Ali, I am still working on the D Udemy course. It will likely be
over 40 hours of tutorial video, based on your book. When
released in the Spring, it should make it easy for newbies to
master learning the D language, which is not trivial. I am
working on it Full Time.
Hopefully, this will put D language back in the "Real" language
category.
-- Brother Bill
More information about the Digitalmars-d-learn
mailing list