user63898
user63898

Reputation: 30885

c++ custom exception added to method gives error

I need my methods to throw custom exceptions but it keeps giving me this error :
error C2059: syntax error : 'string'

I was reading the following link but it doesn't solve my problem:
http://msdn.microsoft.com/en-us/library/t8xe60cf%28VS.80%29.aspx

This is the code I have:

#include <exception>
#include <stdexcept>
#include <string>
#include "Log.h"

LOG_USE()

class Exception : public std::exception 
{
    public:
        explicit Exception(std::string msg)
            : message(msg)
        {}
        ~Exception()
        {}

        virtual const char* what() const  throw() 
        {
            LOG_MSG(message) // write to log file
            return message.c_str();
        }

    private:
        std::string message;
};

#endif

Somewhere in my app I have methods that look like this:

.....
....
void view::setDisplayView(ViewMode mode) throw(Exception("setDisplayView error"))
{
    ;
}
....
....

What am I doing wrong here?
I'm using Visual Studio 2008 on 32-bit Windows XP.

Upvotes: 1

Views: 618

Answers (1)

Eran
Eran

Reputation: 22020

You're not using exception specification correctly. That throw, which follows the declaration of setDisplayView, should only contain a type (in your case, Exception), not an object (which is what you get with that Exception("setDisplayView error")).

Now, having that said, exception specifications are deprecated in C++11, and have not been considered a useful feature before. Better just omit that throw(Exception("setDisplayView error")). Use exception specifications only if you're not going to throw anything. In that case, the new syntax to use would be nothrow.

Edit:

To signify the exception has been thrown from setDisplayView, you must pass that information to the exception when it's created -

void view::setDisplayView(ViewMode mode)
{
     if (badThingHappened())
          throw Exception("setDisplayView error");
}

There are various non-standard techniques to find the origin of the exception when catching it, you can find some here. Using exception specification is just not one of them...

Upvotes: 4

Related Questions