Programming in D page 217 - unittests for custom exceptions

Brother Bill brotherbill at mail.com
Wed Jan 21 18:55:24 UTC 2026


On Wednesday, 21 January 2026 at 17:56:33 UTC, Erdem wrote:
> On Wednesday, 21 January 2026 at 16:32:26 UTC, Brother Bill 
> wrote:
>
>> My question is why isn't the unittest passing it?
>
> I tested the code you provided.
>
> ```d
> import std;
>
> class UnequalLengths : Exception
> {
> 	this(string msg, string file = __FILE__, size_t line = 
> __LINE__)
> 	{
> 		super(msg, file, line);
> 		writeln("Unequal lengths");
> 	}
> }
>
> class RangeError : Exception
> {
> 	this(string msg, string file = __FILE__, size_t line = 
> __LINE__)
> 	{
> 		super(msg, file, line);
> 		writeln("Range error");
> 	}
> }
>
> int[] average(int[] a, int[] b)
> {
>     int[] average;
>     if (a.length != b.length)
>         throw new UnequalLengths("Unequal lengths");
>     return average;
> }
>
> unittest
> {
> 	assertThrown!UnequalLengths(average([1], [1, 2]));
> 	assertNotThrown!RangeError(average([], []));
> }
> ```
>
>
> I compiled the application with the following compiler options.
>
> ```bash
> dmd -unittest -main
> ```
>
> The unit tests seem to be successful.
>
> ```bash
> Unequal lengths
> 1 modules passed unittests
> ```

I got it working.
1. On Linux Fedora 43, dmd -unittest -main didn't work.
2. Need to add in main().
3. Now it works:  $ dub test --force
    The unit tests now pass.

Thanks, Brother Bill


More information about the Digitalmars-d-learn mailing list