C'è un modo per determinare se si sta verificando un'eccezione?
-
02-07-2019 - |
Domanda
In un distruttore, c'è un modo per determinare se un'eccezione è attualmente in fase di elaborazione?
Soluzione
Puoi usare std :: uncaught_exception (), ma potrebbe non fare quello che pensi: vedi GoTW # 47 per ulteriori informazioni.
Altri suggerimenti
Come ha detto Luc, puoi usare std :: uncaught_exception (). Ma perché vuoi saperlo? In ogni caso, i i distruttori non dovrebbero mai generare eccezioni !
Puoi utilizzare la Boost Test Library . Guarda qui un piccolo esempio:
struct my_exception1
{
explicit my_exception1( int res_code ) : m_res_code( res_code ) {}
int m_res_code;
};
struct my_exception2
{
explicit my_exception2( int res_code ) : m_res_code( res_code ) {}
int m_res_code;
};
class dangerous_call {
public:
dangerous_call( int argc ) : m_argc( argc ) {}
int operator()()
{
if( m_argc < 2 )
throw my_exception1( 23 );
if( m_argc > 3 )
throw my_exception2( 45 );
else if( m_argc > 2 )
throw "too many args";
return 1;
}
private:
int m_argc;
};
void translate_my_exception1( my_exception1 const& ex )
{
std::cout << "Caught my_exception1(" << ex.m_res_code << ")"<< std::endl;
}
void translate_my_exception2( my_exception2 const& ex )
{
std::cout << "Caught my_exception2(" << ex.m_res_code << ")"<< std::endl;
}
int
cpp_main( int argc , char *[] )
{
::boost::execution_monitor ex_mon;
ex_mon.register_exception_translator<my_exception1>(
&translate_my_exception1);
ex_mon.register_exception_translator<my_exception2>(
&translate_my_exception2);
try{
// ex_mon.detect_memory_leak( true);
ex_mon.execute( ::boost::unit_test::callback0<int>(
dangerous_call( argc ) ) );
}
catch ( boost::execution_exception const& ex ) {
std::cout << "Caught exception: " << ex.what() << std::endl;
}
return 0;
}
Devi scavare nella documentazione. È una libreria molto potente per testare il tuo software! Ad ogni modo, con l'aiuto di Boost puoi catturare qualsiasi tipo di eccezione innescata ovunque nel tuo test funzionale!
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow