添加到方法的c ++自定义异常会产生错误

时间:2012-07-02 06:11:34

标签: c++ exception inheritance

我需要我的方法来抛出自定义异常 但它一直给我这个错误:
error C2059: syntax error : 'string'

我正在阅读以下链接,但它并没有解决我的问题:
     http://msdn.microsoft.com/en-us/library/t8xe60cf%28VS.80%29.aspx

这是我的代码:

#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

在我的应用程序的某个地方,我的方法看起来像这样:

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

我在这里做错了什么?
我在32位Windows XP上使用Visual Studio 2008。

1 个答案:

答案 0 :(得分:4)

您没有正确使用异常规范。遵循throw声明的setDisplayView应该只包含一个类型(在您的情况下为Exception),而不是一个对象(这是您使用{{1} })。

现在,说到这里,异常规范在C ++ 11中已被弃用,之前并未被认为是一个有用的功能。最好省略Exception("setDisplayView error")。只有在你不打算抛出任何东西时才使用异常规范。在这种情况下,要使用的新语法是nothrow

编辑:

要表示已从throw(Exception("setDisplayView error"))抛出异常,您必须在创建异常时将该信息传递给异常 -

setDisplayView

在捕获异常时,有各种非标准技术可以找到异常的来源,你可以找到一些here。使用异常规范只不是其中之一......