У меня есть программа, которая выдает исключение, которое перехватывается в некоторых конфигурациях (Suse Linux, g ++ версия 4.4.1), как и ожидалось, но, очевидно, не перехватывается в другой, здесь: SunOS 5.10, g ++ версия 3.3.2. Ниже приведена реализация моего класса исключений:
CException.hpp:
#ifndef _CEXCEPTION_HPP
#define _CEXCEPTION_HPP
#include <string>
#include <sstream>
#include <exception>
#include <stdlib.h>
#include <iostream>
class CException : public std::exception {
public:
CException();
CException(const std::string& error_msg);
CException( const std::stringstream& error_msg );
CException( const std::ostringstream& error_msg );
virtual ~CException() throw();
const char* what() const throw();
static void myTerminate()
{
std::cout << "unhandled CException" << std::endl;
exit(1);
};
private:
std::string m_error_msg;
};
CException.cpp:
#include "CException.hpp"
#include <string>
#include <sstream>
CException::CException()
{
std::set_terminate(myTerminate);
m_error_msg = "default exception";
}
CException::CException(const std::string& error_msg)
{
std::set_terminate(myTerminate);
m_error_msg = error_msg;
}
CException::CException(const std::stringstream& error_msg)
{
std::set_terminate(myTerminate);
m_error_msg = error_msg.str();
}
CException::CException(const std::ostringstream& error_msg)
{
std::set_terminate(myTerminate);
m_error_msg = error_msg.str();
}
CException::~CException() throw()
{
}
const char* CException::what() const throw()
{
return m_error_msg.c_str();
}
#endif /* _CEXCEPTION_HPP */
К сожалению, мне не удалось создать простую программу для воспроизведения проблемы, но я постараюсь набросать код.
Исключение выдается в функции foo()
в каком-то файле Auxiliary.cpp
:
std::ostringstream errmsg;
//...
errmsg << "Error occured.";
throw CException( errmsg );
Функция foo()
используется в основной программе:
#include Auxiliary.hpp
//...
int main( int argc, char** argv )
{
try {
//...
foo();
} catch ( CException e ) {
std::cout << "Caught CException" << std::endl;
std::cout << "This is the error: " << e.what( ) << std::endl;
} catch ( std::exception& e ) {
std::cout << "std exception: " << e.what( ) << std::endl;
} catch ( ... ) {
std::cout << "unknown exception: " << std::endl;
}
Я вижу, что исключение не перехватывается при выходе из программы с печатью unhandled CException
, которая определяется myTerminate()
.
Я безуспешно пытался использовать опцию -fexceptions
для компилятора GNU. Параметры компилятора на самом деле одинаковы в обеих системах.
В данный момент я просто не могу понять, в чем проблема. Любые идеи приветствуются. Спасибо!