C++ 具有char*构造函数的异常类
我在VS2008上遇到了以下代码C++ 具有char*构造函数的异常类,c++,visual-studio,c++11,gcc,C++,Visual Studio,C++11,Gcc,我在VS2008上遇到了以下代码 if (!CreateProcess( NULL, const_cast<LPWSTR>(ss.str().c_str()), NULL, NULL, FALSE, CREATE_NO_WINDOW|NORMAL_PRIORITY_CLASS,
if (!CreateProcess( NULL,
const_cast<LPWSTR>(ss.str().c_str()),
NULL,
NULL,
FALSE,
CREATE_NO_WINDOW|NORMAL_PRIORITY_CLASS,
NULL,
NULL,
&si,
&pi))
{
throw std::exception("Unable to format Device");
}
在调查这个问题时,我注意到VisualStudio有一个文件异常,它确实有一个异常类,并且接受char*。有些定义如下所示
__CLR_OR_THIS_CALL exception();
__CLR_OR_THIS_CALL exception(const char *const&);
__CLR_OR_THIS_CALL exception(const char *const&, int);
__CLR_OR_THIS_CALL exception(const exception&);
exception& __CLR_OR_THIS_CALL operator=(const exception&);
virtual __CLR_OR_THIS_CALL ~exception();
virtual const char * __CLR_OR_THIS_CALL what() const;
我的问题是我应该如何在mingwgcc上规避这个构建问题?我是否应该创建一个从std::runtime\u error继承的新类,并将其抛出?观点在这里起作用。问题是
std::exception
没有接受字符串参数的构造函数;这是一个MSVC扩展。我认为有两种方法可以做到这一点:
std::exception
throw std::exception();
缺点是您不会收到描述性错误消息
如果错误消息很重要,则不能直接使用std::exception
。在这种情况下,您可以使用std::logic_error
或std::runtime_error
,它们继承std::exception
,并且确实有构造函数接受字符串参数,所以
throw std::runtime_error("Unable to format Device");
可能已经解决了这个问题catch
捕获std::exception
的子句也将捕获std::runtime\u错误
。但是,有一个潜在的问题:catch
子句catchstd::runtime\u error
不会捕获std::exception
,但会捕获这个
这似乎有点像一个角落的情况,完全有可能这对你来说不是一个问题。但是,如果在调用堆栈中有一个catch
子句捕获std::runtime\u error
但不应捕获此代码引发的异常,则可以从接受字符串参数的std::exception
派生自己的异常类。因为类是新的,所以它不会被现有的catch
子句捕获。例如:
class descriptive_exception : public std::exception {
public:
descriptive_exception(std::string const &message) : msg_(message) { }
virtual char const *what() const noexcept { return msg_.c_str(); }
private:
std::string msg_;
}
然后
throw descriptive_exception("Unable to format Device");
这可以说不是很漂亮,也不太可能是必需的,因此更可能的解决方案是使用std::runtime\u error
或std::logic\u error
(或从其中一个派生的类)
无论是
std::logic_error
还是std::runtime_error
更合适,都不是很清楚;在这种情况下,我可能会使用std::runtime\u error
,因为该错误在理论上似乎不可预测,但鉴于std::domain\u error
和std::future\u error
源自std::logic\u error
,它在该层次结构中不会完全不合适。我认为这是一个观点。代码>:ST::例外:(conchchar)< /> >不是C++标准,而是MS专用的
throw descriptive_exception("Unable to format Device");