Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline throw() method in C++

Tags:

c++

gcc

throw

I am trying to define a really simple exception class. Because it is so simple I want to keep it in the .h file only, but the compiler doesn't like throw(). The code:

#include <exception>
#include <string>

class PricingException : public virtual std::exception
{
private:
    std::string msg;
public:
        PricingException(std::string message) : msg(message) {}
        const char* what() const throw() { return msg.c_str(); }
        ~PricingException() throw() {}
};

GCC gives the following errors:

/home/ga/dev/CppGroup/MonteCarlo/PricingException.h:13: error: expected unqualified-id before ‘{’ token
/home/ga/dev/CppGroup/MonteCarlo/PricingException.h:14: error: expected unqualified-id before ‘{’ token

for lines with throw(). Any idea how to fix it?

EDIT

I tried to remove the bodies of the problematic methods, i.e.

virtual ~PricingException() throw();// {}

And now I get even more weird error message:

/home/ga/dev/CppGroup/MonteCarlo/PricingException.h:14: error: looser throw specifier for ‘virtual PricingException::~PricingException()’
/usr/include/c++/4.5/exception:65: error:   overriding ‘virtual std::exception::~exception() throw ()’

It just ignored my throw specifier!

like image 631
Grzenio Avatar asked Mar 29 '11 12:03

Grzenio


1 Answers

Try the C++0x syntax instead, g++ 4.5 may be recent enough to support it:

const char* what() const noexcept { return msg.c_str(); }

However, this shouldn't matter (wording from draft 3242, section [except.spec]:

Two exception-specifications are compatible if:

  • both are non-throwing (see below), regardless of their form,
  • both have the form noexcept(constant-expression) and the constant-expressions are equivalent,
  • one exception-specification is a noexcept-specification allowing all exceptions and the other is of the form throw(type-id-list), or
  • both are dynamic-exception-specifications that have the same set of adjusted types.

.

If a virtual function has an exception-specification, all declarations, including the definition, of any function that overrides that virtual function in any derived class shall only allow exceptions that are allowed by the exception-specification of the base class virtual function.

.

A function with no exception-specification or with an exception-specification of the form noexcept(constant-expression) where the constant-expression yields false allows all exceptions. An exception-specification is non-throwing if it is of the form throw(), noexcept, or noexcept(constant-expression) where the constant-expression yields true. A function with a non-throwing exception-specification does not allow any exceptions.

So try a newer build of g++, where these changes may be more completely implemented.

like image 192
Ben Voigt Avatar answered Sep 20 '22 02:09

Ben Voigt