Why Testing Exception Throws?

Introduction

Previously, I had some difficulties in understanding why exceptions have to be tested in unit tests. It turns out that I tended to carry some incorrect assumptions about exceptions and treated them differently from the other code, even if I know I should have not been doing that.

In this blog post, I will discuss why testing exceptions are important.

Exceptions VS Termination

Exceptions are no different from the other part of the normal program and they are meant to be caught and handled. Otherwise we should just terminate the program using std::terminate instead, because an uncaught exception will terminate the program anyway.

This is also the idea of noexcept specifier in C++ class member functions. The C++ class member functions with noexcept specifier are guaranteed not to throw exceptions, so the developers do not have to catch and handle exceptions for them.

Because exceptions are meant to be caught and handled, we should test that the exceptions are thrown as expected, otherwise the exceptions might fail to be caught resulting in program termination, or might be caught and handled incorrectly.

Why Testing Exception Throws?

Expect Throw

To capture the exceptions and handle them correctly, the type of the exceptions should be expected. If an unexpected exception is thrown, it will not be captured correctly and the program will terminate.

Expect No Throw

Because exceptions are meant to be caught and handled, if an exception is thrown from a place where it is not expected, it will not be caught and handled correctly, and the program will terminate. To ensure some code will not throw exceptions, we should test that the code will not throw exceptions.

Conclusions

Exceptions are just normal code. Testing exceptions are not different from testing the return values of functions.

Author

Lei Mao

Posted on

08-27-2024

Updated on

08-27-2024

Licensed under


Comments