int foo() const throw(Exception);
我找到了这两个链接:
- http://www.cplusplus.com/doc/tutorial/exceptions/
- http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fcplr156.htm
int foo() throw(int) {
throw char; // Totally unrelated classes, not types in real
}
问题3:函数/方法不应该抛出任何异常。我至少找到了两种(三种,针对不同编译器的替代语法)指定不抛出异常的方法:
int foo() throw();
int foo() __attribute(nothrow)__
适用于gccint foo() nothrow
适用于Visual C++
哪一种是“正确”的?它们有什么区别?我应该使用哪一个?
问题4:“标准异常”,bad_alloc
,bad_cast
,bad_exception
,bad_typeid
和ios_base::failure
。
好的,bad_alloc
很容易理解,我知道如何(更重要的是何时)使用它(将其添加到异常规范中),但其他异常呢?它们中没有一个真正让人想起来...它们与哪些“代码片段”相关联?就像bad_alloc
与new char[500000]
相关联一样。
问题5:如果我有一个异常类层次结构,例如:
class ExceptionFileType {
virtual const char * getError() const = 0;
};
class ExceptionFileTypeMissing : public ExceptionFileType {
virtual const char *getError() cosnt {
return "Missing file";
}
}
我应该使用:
int foo() throw(ExceptionFileType);
或者:
int foo() throw(ExceptionFileTypeMissing,ExceptionFileTypeNotWritable,ExceptionFileTypeNotReadable,...)
注意:带有参考文献的答案会很棒。我正在寻找好的实践技巧。
注:本文提供的参考资料将会很有用。我正在寻找一些好的实践技巧。
throw()
,但在C++11中已被noexcept
取代。 - Cat Plus Plus