Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

stl - Custom Exceptions in C++

I've been trying to make some custom exception classes for a C++ library I'm working on. These custom exceptions capture extra info, such as file,line number,etc, needed for debugging, if for some reason while testing an exception is not caught in the right place. However most people seem to recommend inheriting from the std::exception class in the STL, which I agree with, but I was wondering maybe it would be better to use multiple inheritance to inherit from each of the derived std::exception classes (eg. std::runtime_error) and a custom exception class, as in the code below?

Another thing, how does one go about copy constructors and assignment operators in exception classes? Should they be disabled?

class Exception{
    public:
        explicit Exception(const char *origin, const char *file, 
                           const int line, const char *reason="", 
                           const int errno=0) throw();

        virtual ~Exception() throw();

        virtual const char* PrintException(void) throw();

        virtual int GetErrno(void);

    protected:
        std::string m_origin;
        std::string m_file;
        int m_line;
        std::string m_reason;
        int m_errno;
}; 

class RuntimeError: public virtual std::runtime_error, public Exception{
    public:
              explicit RuntimeError(const char *origin, const char *file, 
                                    const int line, const char *reason="", 
                                    const int errno=0) throw();
        virtual ~RuntimeError() throw();
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I was wondering maybe it would be better to use multiple inheritance to inherit from each of the derived std::exception classes

Note that this is a problem, due to the fact that the exceptions in the standard library derive non-virtually from each other. If you introduce multiple inheritance, you get the dreaded diamond exception hierarchy without virtual inheritance and won't be able to catch derived exceptions by std::exception&, since your derived exception class carries two subobjects of std::exception, making std::exception an "ambiguous base class".

Concrete example:

class my_exception : virtual public std::exception {
  // ...
};

class my_runtime_error : virtual public my_exception
                       , virtual public std::runtime_error {
  // ...
};

Now my_runtime_error derives (indirectly) from std::exception twice, once through std::run_time_error and once through my_exception. Since the former doesn't derive from std::exception virtually, this

try {
  throw my_runtime_error(/*...*/);
} catch( const std::exception& x) {
  // ...
}

won't work.

Edit:

I think I've seen the first example of an exceptions class hierarchy involving MI in one of Stroustrup's books, so I concluded that, in general, it is a good idea. That the std lib's exceptions do not derive virtually from each other I consider as a failure.

When I last designed an exception hierarchy, I used MI very extensively, but did not derive from the std lib's exception classes. In that hierarchy, there were abstract exception classes which you defined so your users could catch them, and corresponding implementation classes, derived from these abstract classes and from an implementation base class, which you would actually throw. To make this easier, I defined some templates which would do all the hard work:

// something.h
class some_class {
private:
  DEFINE_TAG(my_error1); // these basically define empty structs that are needed to 
  DEFINE_TAG(my_error2); // distinguish otherwise identical instances of the exception 
  DEFINE_TAG(my_error3); // templates from each other (see below)
public:
  typedef exc_interface<my_error1>  exc_my_error1;
  typedef exc_interface<my_error2>  exc_my_error2;
  typedef exc_interface<my_error3,my_error2> // derives from the latter
                                    exc_my_error3;

  some_class(int i);
  // ...
};

//something.cpp
namespace {
  typedef exc_impl<exc_my_error1> exc_impl_my_error1;
  typedef exc_impl<exc_my_error2> exc_impl_my_error2;
  typedef exc_impl<exc_my_error3> exc_impl_my_error3;
  typedef exc_impl<exc_my_error1,exc_my_error2> // implements both
                                  exc_impl_my_error12;
}
some_class::some_class(int i)
{
  if(i < 0) 
    throw exc_impl_my_error3( EXC_INFO  // passes '__FILE__', '__LINE__' etc.
                            , /* ... */ // more info on error
                            ); 
}

Looking back at this now, I think I could have made that exc_impl class template derive from std::exception (or any other class in the std lib exception hierarchy, passed as optional template parameter), since it never derives from any other exc_impl instance. But back then this wasn't needed, so it never occurred to me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...