Programming in D page 217 - unittests for custom exceptions

Erdem zayifakimkolu at gmail.com
Wed Jan 21 17:56:33 UTC 2026


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
```


More information about the Digitalmars-d-learn mailing list