Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++20: A question about dynamic exception specification

Reference: Dynamic exception specification (until C++17)

I am writing some test code and would like to specify a throw exception of type std::bad_alloc (std::bad_alloc) for a template function, which would try and allocate memory dynamically for the merge of two sorted arrays of type T:

template<typename T, size_t N>
std::unique_ptr<std::array<T,N>>merge2SortedArrays(std::array<std::array<T,N>,2>) throw(bad_alloc);

The objective is that the user of the function template should know that a bad_alloc exception could result if memory allocation fails, and should have a corresponding catch block in the invoking code to handle this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am using g++ for compilation and using the compile-time flag -std=c++20.

In the link related to dynamic exception specification above, it has been stated that this construct is only supported until C++17.

So is there an alternative in C++20? Or could we continue using the construct?

TIA

>Solution :

You can use the noexcept specifier:

  • noexcept(false) would specify a potentially throwing function.
  • noexcept(true) or just noexcept would specify a non-throwing function.

Other than through documentation, it’s not possible to specify what exception type a function may throw. It’s either true or false.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading