0

There are many ways to create a new exception that is derived from some other exception. One way is to use something like this

struct MyException : public exception
{
  const char * what () const throw ()
  {
    return "C++ Exception";
  }
};

and another way is to call the constructor of the base class.

class My:public runtime_error
{
public:
    My(string s):runtime_error(s){}
};

The second method obviously gives me the advantage to insert (at creation) the string that is output by the what() method. My question is which method should I prefer and whether I need to use the first method at all.

Slazer
  • 4,750
  • 7
  • 33
  • 60

1 Answers1

1

In case you really want to use a string literal only, you could go for the first option, however, the second is the default you see everywhere.

It's not the case ATM, however, if they decide to expand the C++ exception class later on, having a second method based on the exception string you'd run into problems. So I don't see any reason to use the first version at all.

BTW: what() is noexcept not throw()

D.R.
  • 20,268
  • 21
  • 102
  • 205
  • "const char * what () const noexcept" does not compile. I noticed this "noexcept version" at "http://www.cplusplus.com/reference/exception/exception/exception/" but it fails to compile. – Slazer Aug 02 '13 at 20:56
  • 1
    What's the compiler error? Most probably your compiler is not fully C++11 ready. – D.R. Aug 02 '13 at 20:57
  • The error together with the code is at http://pastebin.com/PQ8ZhV24 The compiler is "g++ (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2)" – Slazer Aug 02 '13 at 20:59
  • I'm using VS12, however, a little bit of googling brought this up: http://stackoverflow.com/questions/15721544/destructors-and-noexcept So probably you just have to update gcc. – D.R. Aug 02 '13 at 21:03
  • I just tried it with -std=c++11 and it works! Anyway, what is wrong with throw? – Slazer Aug 02 '13 at 21:04
  • 1
    @Slazer Did you use appropriate flag to enable C++11? Because `what()` is declared with macro `_GLIBCXX_USE_NOEXCEPT` that expands either into `noexcept` or into `throw()` depending on the flag. – lapk Aug 02 '13 at 21:05
  • 1
    @Slazer http://stackoverflow.com/questions/12833241/difference-between-c03-throw-specifier-c11-noexcept – D.R. Aug 02 '13 at 21:07
  • @D.R. Thanks, it's exactly I was looking for. One more thing - what did you mean by ATM? – Slazer Aug 02 '13 at 21:10
  • ATM = at the moment. However, don't be worried, I don't think somebody is going to change the exception class anytime soon : ) – D.R. Aug 02 '13 at 21:13