异 常 处 理

发布时间:2006-06-28 04:35     点击:
分页:上一页  1 2 3 4 5 6 7 8 9 [10]  下一页

catch(std::exception& std_ex) //bad_alloc exception is always handled here

{

//...handle the exception

}

catch(std::bad_alloc& alloc_failure) //unreachable

{

cout<<"memory allocation failure";

}

重新抛出异常

异常的抛出表明了一种反常的状态。先捕获到异常的handler试图解决这个问题,但是它如果没有成功或者只完成了部分恢复,那么它可以重新抛出这个异常,让更高一层的try block来处理它。基于这种目的,try blocks可以在一个分等级的顺序上进行嵌套,使得一个从低层重新抛出的异常能够被重新捕获。重新抛出用一个没有操作数的throw语句来表示。例如:

#include <iostream>

#include <string>

using namespace std;

enum {SUCCESS, FAILURE};

class File

{

public: File (const char *) {}

public: bool IsValid() const {return false; }

public: int OpenNew() const {return FAILURE; }

};

class Exception {/*..*/}; //general base class for exceptions

class FileException: public Exception

{

public: FileException(const char *p) : s(p) {}

public: const char * Error() const { return s.c_str(); }

private: string s;

};

void func(File& );

int main()

{

try //outer try

{

File f ("db.dat");

func; // 1

}

catch(...) // 7

//this handler will catch the re-thrown exception;

//note: the same exception type is required

{

cout<<"re-thrown exception caught";

}

return 0;

}

void func(File & f)

{

try //inner try

{

if (f.IsValid() == false )

throw FileException("db.dat"); // 2

}

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