在C++中,您可以通过使用异常说明符指定函数可能会也可能不会抛出异常.例如:
void foo() throw(); // guaranteed not to throw an exception
void bar() throw(int); // may throw an exception of type int
void baz() throw(...); // may throw an exception of some unspecified type
Run Code Online (Sandbox Code Playgroud)
由于以下因素,我对实际使用它们表示怀疑:
你认为应该使用异常说明符吗?
请回答"是"或"否"并提供一些理由来证明您的答案.
C++为已检查的异常提供了语法,例如:
void G() throw(Exception);
void f() throw();
Run Code Online (Sandbox Code Playgroud)
但是,Visual C++编译器不检查它们; throw标志被忽略了.在我看来,这使得异常功能无法使用.所以我的问题是:有没有办法让编译器检查异常是否被正确捕获/重新抛出?例如,Visual C++插件或不同的C++编译器.
PS.我希望编译器检查异常是否被正确捕获,否则你最终会遇到必须对每个函数调用进行捕获的情况,即使它们明确声明它们不会抛出任何东西.
更新:当抛出标有throw()的函数时,Visual C++编译器确实显示警告.这很好,但令人遗憾的是,当你调用可能抛出的子程序时,警告不会出现.例如:
void f() throw(int) { throw int(13); }
void h() throw() { g(); } //no warning here!
Run Code Online (Sandbox Code Playgroud) 我在使用C++代码时遇到了问题,这些代码意外地对调用者抛出异常.读取用于查看是否抛出异常的模块的每一行并不总是可行或实际的,如果是,则抛出异常类型.
是否存在处理此问题的成语或"最佳实践"?
我想到了以下几点:
在我们的doxygen文档中,我们可以在每个预期会抛出异常及其类型的函数中添加注释.
我们可以安装应用程序try/catch(...).
使用例外规范
有这些方法的经验,还是我不知道的任何其他方法?
std :: exception类定义如下
exception() throw() { }
virtual ~exception() throw();
virtual const char* what() const throw();
Run Code Online (Sandbox Code Playgroud)
throw()语法在声明中的含义是什么?可以throw()接受参数吗?什么没有参数意味着什么?
我正在经历C++ FAQ 2nd Edition, FAQ 9.04- What is an exception specification?.
在那里,提到如果我们从其签名指定一组预定义异常类型的函数抛出一个意外异常,它应该调用unexpected()->terminate()->abort().但是我的程序捕获了意外的异常而不是abort()它,为什么?
#include<iostream>
using namespace std;
class Type1{};
class Type2{};
class Type3{};
void func() throw(Type1, Type2)
{
throw Type3();
}
int main()
{
try{
func();
}
catch (Type1 &obj1)
{
cout << "Type1 is caught" << endl;
}
catch (Type2 &obj2)
{
cout << "Type2 is caught" << endl;
}
catch (Type3 &obj3)
{
cout << "Type3 is caught" << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我得到的输出 …
在下面的成员函数声明中,我无法理解为什么在同一个声明中有两个函数what()和throw()?这是什么意思?我是c ++的初学者,我可能没有研究过这个概念.请帮帮我或指出我必须阅读的材料.
virtual const char* what() const throw() {}
Run Code Online (Sandbox Code Playgroud) 我想知道是否有一些编译器参数,最好是在gcc(g ++)中将缺少try/catch块视为错误.这是java中的标准行为,我总是喜欢它.