分页:
上一页 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] 下一页