//first chance to cope with the exception
{
cout<<"invalid file specification" <<fe.Error()<<endl;
if (f.OpenNew() != SUCCESS) (5)
//re-throw the original exception and let a higher handler deal with it
throw; // 6
}
}
在上面的例子中,函数func()在main()中的try block里被调用(1)。第二个在func()中的try block抛出一个FileException类型的异常(2)。这个异常被func()内的catch block所捕获(3)。那个catch block试图通过打开一个新文件进行补救,但是失败了(5),并且FileException异常被重新抛出(6)。最终,那个重新抛出的异常被main()中的catch(…)所捕获(7)。
Function try Blocks
Function try blocks是一个函数体本身就含有一个try block以及它的相关handler的函数。比如:
class Bad{};
void foo()try
{
throw Bad();
}
catch(...)
{
std::cout<<"error catch!!";
}
function try block使得一个handler能够捕获构造函数中以及初始化列表中发生的异常。然而,它并不像普通异常的handler,function try block很少能够捕获异常继续对象的构建。这是因为被部分构造的对象要被销毁。另外,一个function try block的handler不能执行返回语句(或者说,handler必须通过一个throw离开)。那么究竟function try block的用处是什么呢?handler使得你可以抛出另一个异常而不是你刚才捕获的那个,这样可以阻止一个违背exception specification的情况发生。例如:
class X{};
C::C(const std::string& s) throw (X) // allowed to throw X only
try
: str(s) // str's constructor might throw a bad_alloc exception,
// might violate C's exception specification
{
// constructor function body
}
catch (...) //handle any exception thrown from ctor initializer or ctor body
{
//...
throw X(); //replace bad_alloc exception with an exception of type X