Custom exceptions violate unittest

Steven Schveighoffer schveiguy at gmail.com
Sun Nov 30 19:18:13 UTC 2025


On Sunday, 30 November 2025 at 14:00:12 UTC, Brother Bill wrote:
> In book "Programming in D", on page 217.
> My concern is why the assertThrown!UnequalLengths unit test 
> does not catch the custom Exception of UnequalLengths.
>
> Is this a bug or a feature?
>
> source/app.d
> ```d
> import std.stdio : writeln;
> import std.exception : assertThrown, assertNotThrown;
>
> void main()
> {
>
> }
>
> 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("Unequal lengths");
> 	}
> }
>
> void average(int[] a, int[] b)
> {
> 	throw new UnequalLengths("Unequal lengths");
> }
>
> unittest
> {
> 	// Must throw UnequalLengths for uneven slices
> 	assertThrown!UnequalLengths(average([1], [1, 2]));
>
> 	// Must not throw RangeError for empty slices (it may throw 
> other types of exceptions)
> 	assertNotThrown!RangeError(average([], []));
> }
>
> ```

It may throw other exceptions. But those exceptions are *not 
caught* by `assertNotThrown`. From the docs:

> Asserts that the given expression does not throw the given type 
> of Throwable. If a Throwable of the given type is thrown, it is 
> caught and does not escape assertNotThrown. Rather, an 
> AssertError is thrown. **However, any other Throwables will 
> escape.**

I can imagine a scenario where you have an exception that is a 
derivative of another exception. Let's say I wanted to assert 
that an `Exception` is thrown, but that it is not an 
`UnequalLengths` exception. Then you would do:

```d
assertThrown!Exception(assertNotThrown!UnequalLengths(...));
```

But other than that, specifying that a specific exception is not 
thrown seems to be of very limited value.

FWIW, I'd change the message in those two writelns so you can 
tell which one is written.

-Steve


More information about the Digitalmars-d-learn mailing list