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.
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 justnoexceptwould 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.