I´m moving from C# to C++ so forgive me if the question is basic or has some misconceptions...
I want to build my own exception to be used on my try/catch blocks. I need to report a custom exception code, a custom exception message and a custom exception source origin - I may have all or some of these parameters.
So I´ve built that class:
CommonException.hpp
namespace exceptionhelper
{
class CommonException : public std::exception {
public:
CommonException();
CommonException(std::string message);
CommonException(std::string source, std::string message);
CommonException(int code, std::string source, std::string message);
virtual ~CommonException();
const char *what() const throw();
private:
int exceptionCode;
std::string exceptionSource;
std::string exceptionMessage;
};
}
And the implementation:
CommonException.cpp
namespace exceptionhelper {
CommonException::CommonException() {
exceptionCode = 0;
exceptionMessage = "No message.";
exceptionSource = "No source.";
}
CommonException::CommonException(std::string message) {
exceptionCode = 0;
exceptionMessage = message;
exceptionSource = "No source.";
}
CommonException::CommonException(std::string source, std::string message) {
exceptionCode = 0;
exceptionMessage = message;
exceptionSource = source;
}
CommonException::CommonException(int code, std::string source, std::string message) {
exceptionCode = code;
exceptionMessage = message;
exceptionSource = source;
}
CommonException::~CommonException() {
}
const char *CommonException::what() const throw()
{
std::stringstream s;
s << "Code : " << exceptionCode << std::endl;
s << "Source : " << exceptionSource << std::endl;
s << "Message : " << exceptionMessage << std::endl;
return s.str().c_str();
}
}
And finally my implementation:
main ()
{
try {
... code ...
throw new CommonException(10, "here", "test exception");
}
catch (const std::exception &exc)
{
std::cerr << "Exception detected:" << std::endl;
std::cerr << exc.what();
}
catch (...)
{
std::cerr << "Unknown exception called." << std::endl;
throw;
}
}
For some reason I´m getting this result:
Unknown exception called.
terminate called after throwing an instance of 'linuxcommon::exceptionhelper::CommonException*'
Aborted (core dumped)
Questions:
a) Why am I not catching my custom exception ? b) I´m pretty sure there are better ways to do this exception handling, but I cannot figure that out yet...
Thanks for helping...