1. Introduction
Inside a
block, we should have access to the
of what was thrown. Currently there is no portable way to get the
from a
, and so if an object is thrown of intrinsic type or a non-polymorphic class type, and caught in a
block, the type of the exception object is unknown.
2. Motivation
2.1. catch (...)
A C++ program can link with a shared library which has incomplete or inaccurate documentation for the exceptions it throws, or the program may link at runtime using
or
to link with a library which it knows very little about. Code in the main program may handle an exception thrown from within the shared library as follows:
#include <exception> // exception, exception_ptr
#include <new> // bad_alloc
#include <typeinfo> // typeid, type_info
extern void SomeLibraryFunction(void) noexcept(false);
int main(void)
{
try
{
SomeLibraryFunction();
}
catch(std::bad_alloc const&)
{
// Attempt safe shutdown when memory is depleted
}
catch(std::exception const &e)
{
std::type_info const &ti = typeid(e);
// As 'std::exception' has a virtual destructor, it is
// a polymorphic type, and so 'typeid' will give us the
// RTTI of the derived class.
}
catch(...)
{
std::exception_ptr const p = std::current_exception();
// We can get a pointer to the exception object, but
// we have no idea of the type of what was thrown
}
}
This proposal will allow us to access the
of the exception object inside a
block, as follows:
catch(...)
{
std::type_info const &ti = std::typeid_except();
}
And also to get the
from any
, as follows:
void Func(std::exception_ptr const &p)
{
std::type_info const &ti = std::typeid_except(p);
std::puts( ti.what() );
}
int main(void)
{
std::exception_ptr p;
try
{
throw std::runtime_error("resources depleted");
}
catch(...)
{
p = std::current_exception();
}
Func(p);
}
Once we have the
, we can perform checks on the name:
catch(...)
{
std::type_info const &ti = std::typeid_except();
if ( std::strstr( ti.name(), "FieryShadow" ) ) return EXIT_FAILURE;
}
The name of the type will of course be mangled and therefore be different on different compilers, but if a class is named 'FieryShadow', then its mangled name will contain 'FieryShadow', hence the function
will work here. However, until a name mangling library is added to the standard library, code to distinguish specifically between type names (e.g. where one class is inside an anonymous namespace) will be platform-specific and non-portable.
2.2. Runtime plugins
A massive program such as 3D modelling software for a desktop computer may allow the installation of 3rd party plugins. These plugins come in the form of a dynamic shared library (e.g. '.dll' on MS-Windows, or '.so' on Apple-macOS) which is loaded at runtime using
or
, and the plugin must export a list of functions expected by the main program, e.g.
and
. One of these exported functions could be
as follows:
std::type_info const *const * Plugin_GetExceptions ( void ) noexcept ;
returns a pointer to a null-terminated array of pointers to the
's of bespoke exceptions thrown from the plugin. When the main program first loads the plugin, the main program populates a global array of these exception types, and the main program consults this array when an exception is caught:
catch(...)
{
std::type_info const &ti = std::typeid_except();
if ( nullptr != plugin_exceptions.find(&ti) )
{
// We have caught one of the 'registered' exception types
}
}
From here, the main program can perform tasks specific to the exception type, such as calling a specific handler function exported by the plugin.
2.3. As a stepping stone
There has been recent discussion about making major additions to
, for example to record the
,
and
of the type. There is the hope that if this current proposal is accepted, it will be used as a stepping stone for future papers, for example to log unknown exceptions and give a hexdump of the exception object. For example we could get a print-out such as the following:
Type of exception object: 5Dummy
Size of exception object: 32
Hex: 46726f6773313233000000000000000000000000000000000000000000000000
ASCII: Frogs123
from the following code:
struct Dummy {
char buf[32];
Dummy(void) : buf("Frogs123") {}
};
try
{
throw Dummy();
}
catch(...)
{
using std::sizeof_type_info
;
using std::get_exception_object_from_exception_pointer
;
std::type_info const &ti = std::typeid_except();
printf("Type of exception object: %s\n" , ti.name());
if ( (0u==sizeof_type_info
(ti)) || (-1==sizeof_type_info
(ti)) ) return;
printf("Size of exception object: %zu\n", sizeof_type_info
(ti));
char unsigned const *const p = get_exception_object_from_exception_pointer
(p);
printf(" Hex: ");
for ( size_t i = 0u; i < sizeof_type_info(ti); ++i )
{
printf("%02x", static_cast(p[i]) );
}
printf("\nASCII: ");
for ( size_t i = 0u; i < sizeof_type_info(ti); ++i )
{
char c = p[i];
if ( !isprint(c) || isspace(c) ) c = ' ';
putchar(c);
}
putchar('\n');
}
This would greatly aid in logging exceptions in both Debug and Release builds, even where C++ code is linked with another language such as Java or C#.
3. Impact on the standard
This proposal is a pure library extension. It does not require changes to the standard components. Just two short paragraphs are to be appended to Section 17.9.7 [support.exception.propagation]. The text addition is less than 60 words, and the addition has no effect on any other part of the standard.
4. Impact on existing code
No existing code becomes ill-formed. The behaviour of all exisiting code is unaffected by this addition to the standard library.
5. Design considerations
5.1. Microsoft SEH
The Microsoft C++ compiler has two kinds of exception:
- C++ exceptions
- SEH exceptions
catch
block -- not even by a catch(...)
block. However if you compile with the /EHa switch, an SEH exception will be caught by a catch(...)
bock. In this case, current_exception()
returns a valid exception_ptr
, however there is no type_info
available for an SEH exception. In any circumstance where type_info
is unavailable, the recommendation is that typeid_except()
and typeid_except(p)
shall return typeid(void)
, or alternatively the type_info
of a special type such as typeid(_s__SE)
.
There is a workaround to ensure that SEH exceptions have
type_info
, and that is to use the function _set_se_translator
to convert SEH exceptions to C++ exceptions as follows:
// Compile with Microsoft C++ compiler with option /EHa
#include <cstdio> // ::sprintf_s, std::puts
#include <exception> // exception
#include <eh.h> // _set_se_translator, _EXCEPTION_POINTERS
class SEH_Exception : public std::exception {
private:
unsigned const var_number;
mutable char var_what[14u + 1u]; // +1 for null terminator
public:
SEH_Exception(unsigned const arg) noexcept : var_number(arg) {}
char const *what(void) const noexcept override
{
static_assert( 0xFFFFFFFF == (unsigned)-1, "unsigned int must be 32-Bit" );
::sprintf_s(this->var_what, "SEH 0x%08x", this->var_number);
return this->var_what;
}
unsigned number(void) const noexcept { return var_number; }
};
void DivideByZero(void) // Throws an SEH exception
{
int volatile x, y = 0;
x = 5 / y; // division by zero throws 0xc0000094
}
void translator(unsigned const u, ::_EXCEPTION_POINTERS*)
{
throw SEH_Exception(u);
}
int main(void)
{
::_set_se_translator( translator );
try
{
DivideByZero();
}
catch(std::exception const &e)
{
std::puts( e.what() );
}
}
5.2. Forced unwinding
The throwing of an exception results in unwinding of the stack, and so normally stack unwinding is accompanied by the presence of an exception object. There are circumstances however in which stack unwinding can take place without an accompanying exception object, and one such circumstance is a forced unwinding. An example of a forced unwinding is where the execution of a thread is abruptly stopped by the invocation of
, as follows:
#include <cstdio> // puts
#include <exception> // exception_ptr
#include <pthread.h> // pthread_create
#include <unistd.h> // sleep
void *Thread_Entry_Point(void*)
{
try
{
for (; /* ever */ ;)
{
std::puts("*");
::sleep(1u);
}
}
catch(...)
{
std::exception_ptr const p = std::current_exception();
if ( false == static_cast<bool>(p) )
{
std::puts("exception_ptr is invalid - might be forced unwinding");
throw;
}
}
return nullptr;
}
int main(void)
{
::pthread_t h;
::pthread_create(&h, nullptr, Thread_Entry_Point, nullptr);
::sleep(3u);
::pthread_cancel(h);
::pthread_join(h, nullptr);
}
In the case of a forced unwinding, the recommendation is that typeid_except()
shall return either typeid(void)
, or the type_info
of a special type which indicates forced unwinding, for example typeid(abi::__forced_unwind)
-- even if current_exception()
returns a null pointer. This is the one scenario in which typeid_except()
and typeid_except( current_exception() )
might not be equivalent.
6. Proposed wording
The proposed wording is relative to [N4950].
In section 17.9.7 [support.exception.propagation], append:
13 type_info const &typeid_except( void ) noexcept;
Returns: A reference to a ‘type_info’ (17.7.3) object for the currently
handled exception, or ‘typeid(void)’ (7.6.1.8) if the currently
handled exception is lacking ‘type_info’.
14 type_info const &typeid_except( exception_ptr const &p ) noexcept;
Returns: A reference to a ‘type_info’ (17.7.3) object for the exception
object referred by ‘p’ (17.9.7.1), or ‘typeid(void)’ (7.6.1.8)
if ‘p’ is a null pointer, or ‘typeid(void)’ if the exception
is lacking ‘type_info’.
7. Acknowledgements
For their feedback and contributions on the mailing list std-proposals@lists.isocpp.org:
Thiago Macieira, Jens Maurer, Jason McKesson, Arthur O'Dwyer, Peter Olsson, Jan Schultke, Lénárd Szolnoki, Matthew Taylor, Ville Voutilainen, Sebastian Wittmeier and the late Edward Catmur (1982-2024).