paz...@gmail.com wrote:
Hi,
I'm trying to create a class "Exception" that will contain some
enumeration specifying cause (why the exception was thrown):
class Exception {
public:
enum Type {
DATABASE_CORRUPTED,
COULD_NOT_READ_TABLE_MAP
} type;
explicit Exception(Type type) : type(type) {}
};
But I don't really know how does the compiler understand:
throw Exception::COULD_NOT_READ_TABLE_MAP
because it doesn't show any errors or even warnings, and
COULD_NOT_READ_TABLE_MAP is not a member of Exception class. Does
anybody know how can this be correct ? Also I would be greatful if you
would share with me your experiences with C++ exceptions (do you create
a class for every situation or do you try to do it like I do / how do
you organize them).
Paul PAZABO Zaborski
One suggestion might be to make your own exceptions by deriving from
std::exception.
Or alternately, by deriving from one of std::exception's derivatives
like std::runtime_error.
That way, you can use a universal catch block to capture any
std::exception, including your own.
std::exception already has a virtual destructor and its already
equipped with a what() non-throwing member function. So its a very
simple construct (change the class names to your liking):
#include <iostream>
#include <ostream>
#include <stdexcept>
class db_corrupted_error : public std::runtime_error
{
public:
db_corrupted_error()
: std::runtime_error("database corrupted") { }
};
class read_table_error : public std::runtime_error
{
public:
read_table_error()
: std::runtime_error("read table map error") { }
};
int main()
{
try {
// do stuff
throw db_corrupted_error(); // testing
} catch ( const std::exception& r_e ) {
std::cerr << "error: " << r_e.what();
std::cerr << std::endl;
}
}
/*
error: database corrupted
*/
Another option is to derive from std::logic_error which is also a
derivative of std::exception.