我应该使用C ++中的异常说明符吗? [英] Should I use an exception specifier in C++?
问题描述
在C ++中,您可以指定函数可以通过使用异常说明符来抛出异常。例如:
In C++, you can specify that a function may or may not throw an exception by using an exception specifier. For example:
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
我怀疑实际使用它们是因为
I'm doubtful about actually using them because of the following:
- 编译器并没有严格执行异常说明符,所以好处不大。
- 如果一个函数违反了一个异常说明符,我认为标准的行为是终止程序。
- 在VS.Net中,它将throw(X)作为throw(...),因此遵守标准并不强。
您认为应该使用例外说明符吗?
请回答yes或no,并提供一些理由来证明您的答案。
Do you think exception specifiers should be used?
Please answer with "yes" or "no" and provide some reasons to justify your answer.
推荐答案
否。
以下是几个示例:
-
模板代码不能用异常规范写入,
Template code is impossible to write with exception specifications,
template<class T>
void f( T k )
{
T x( k );
x.x();
}
副本可能会抛出,参数传递可能会抛出,而<$ c $
The copies might throw, the parameter passing might throw, and x()
might throw some unknown exception.
异常规范倾向于禁止可扩展性。
Exception-specifications tend to prohibit extensibility.
virtual void open() throw( FileNotFound );
可能会演变为
virtual void open() throw( FileNotFound, SocketNotReady, InterprocessObjectNotImplemented, HardwareUnresponsive );
你真的可以写成
throw( ... )
旧代码
当你编写依赖另一个库的代码时,你不知道什么东西出错时可能会做什么。
When you write code which relies on another library, you don't really know what it might do when something goes horribly wrong.
int lib_f();
void g() throw( k_too_small_exception )
{
int k = lib_f();
if( k < 0 ) throw k_too_small_exception();
}
g
,当 lib_f()
throws。这是(在大多数情况下)不是你真正想要的。 std :: terminate()
不应该被调用。总是最好让应用程序崩溃与未处理的异常,您可以从中检索堆栈跟踪,而不是静静/暴力死亡。
g
will terminate, when lib_f()
throws. This is (in most cases) not what you really want. std::terminate()
should never be called. It is always better to let the application crash with an unhandled exception, from which you can retrieve a stack-trace, than to silently/violently die.
写入
Error e = open( "bla.txt" );
if( e == FileNotFound )
MessageUser( "File bla.txt not found" );
if( e == AccessDenied )
MessageUser( "Failed to open bla.txt, because we don't have read rights ..." );
if( e != Success )
MessageUser( "Failed due to some other error, error code = " + itoa( e ) );
try
{
std::vector<TObj> k( 1000 );
// ...
}
catch( const bad_alloc& b )
{
MessageUser( "out of memory, exiting process" );
throw;
}
库只是抛出你自己的异常,你可以使用异常规范来声明你的意图。
Nevertheless, when your library just throws your own exceptions, you can use exception specifications to state your intent.
这篇关于我应该使用C ++中的异常说明符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!