异 常 处 理

发布时间:2006-06-28 04:35     点击:
分页:前10页  上一页  [11] 12 13  下一页

//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
分页:前10页  上一页  [11] 12 13  下一页
版权申明:未经书面授权请勿转载本站信息!!作品版权归所属媒体与作者所有!!
发表评论: 匿名发表 用户名: 查看评论
您将承担一切因您的行为、言论而直接或间接导致的民事或刑事法律责任
留言板管理人员有权保留或删除其管辖留言中的任意内容
本站提醒:不要进行人身攻击。谢谢配合。
在本站搜索相关信息
2003-2005 Ksw123.com All Rights Reserved. - TOP
Copyright © 2006 Ksw123.com. All rights reserved.中国考题网 版权所有