FAQ
for [no.it.programmering.c++]
Alle unntaksklasser bør være utledet fra std::exception,
men i praksis er det ikke alltid slik. For eksempel, i Windows-programmering
kan du få unntak av urelaterte typer fra MFC, ATL og Lotus Notes C++
biblioteket. I stedet for redundante catch-blokker overalt kan
du da bruke én funksjon som oversetter forskjellige unntak til for eksempel
standard unntak, eller strenger:
#include <iostream> // std::cout, std::cerr, std::endl
#include <string> // std::string
#include <stdexcept> // std::exception, std::runtime_error
std::string exceptionText()
{
try
{
throw;
}
catch( char const* s )
{
return s;
}
catch( std::exception const& x )
{
return x.what();
}
catch( ... )
{
std::cerr
<< "Caught an unknown exception, terminating."
<< std::endl;
std::terminate();
}
}
enum exceptionKindEnum { charPointer, stdException };
void test( exceptionKindEnum exceptionKind )
{
try
{
switch( exceptionKind )
{
case charPointer: throw "char pointer";
case stdException: throw std::runtime_error( "std exception" );
}
}
catch( ... )
{
std::cout << "Caught a " << exceptionText() << "." << std::endl;
}
}
int main()
{
test( charPointer );
test( stdException );
}
som gir (skal gi) utskriften
Caught a char pointer.
Caught a std exception.
En feil i Visual C++ 6.0 kompilatoren gjør at denne teknikken ikke kan brukes med den kompilatoren, men feilen er rettet i Visual C++ 7.0.