I have a custom exception hierarchy in C++ to detect unexpected cases in a library I am implementing. The base exception class inherits from std::exception
and all other exception classes derive from this base class.
The header file for the base exception class is as follows:
#ifndef LibException_H_
#define LibException_H_
#include <exception>
class LibException : public std::exception
{
public:
// Sets member_err to err
LibException(const char* err);
virtual ~LibException() throw ();
// Returns member_err.
virtual const char* what() const throw();
protected:
// A description of the error. Should probably set this to private.
const char* member_err;
private:
};
#endif
And here is the header file for one of the derived classes, which is supposed to catch any process related error (I am spawning multiple processes within C++ in the source code, and I am using this class there for error handling):
#ifndef ProcessException_H_
#define ProcessException_H_
#include "Includes/LibException.H"
class ProcessException : public LibException
{
public:
enum Reason
{
NETWORK,
IO,
OTHER,
};
// Calls superclass(err) and sets the two member variables
ProcessException(const char* err, Reason reason,
const char* process_command);
virtual ~ProcessException() throw ();
// Returns a char* pointer to the reason.
//
// E.g. NETWORK = "NETWORK"
// @return: <const char*> member_reason.
const char* getReasonChar() const throw();
// Returns a char* pointer to the spawned process' command (e.g. "ls -a").
//
// @return: member_command.
const char* getCommand() const throw();
protected:
private:
Reason member_reason;
const char* member_command;
};
So one would invoke an error case for the derived class above by writing throw ProcessException("Process exited unexpectedly", ProcessException::NETWORK, process_command);
where process_command
is the string representation for a certain process (e.g. ls -a
).
Does this implementation make sense? How can the above design be improved?
Edit: Moreover I have another exception class called ParseException (very similar to the derived class above) which is thrown when a parser that is parsing a file or a command from the shell fails unexpectedly. I have read that such errors are better handled via assert statements because they don't represent "exceptional" cases. Could anyone please comment on this?