由于构造函数能抛出异常,希望处理在对象的成员在其基类子对象被初始化的
时候抛出的异常
构造函数初始化部分的try块是构造函数的函数体,而相关的catch块紧跟着
构造函数的函数体
//: C01:InitExcept.cpp {-bor}
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Handles exceptions from subobjects.
#include <iostream>
using namespace std;
class Base {
int i;
public:
class BaseExcept {};
Base(int i) : i(i) { throw BaseExcept(); }
};
class Derived : public Base {
public:
class DerivedExcept {
const char* msg;
public:
DerivedExcept(const char* msg) : msg(msg) {}
const char* what() const { return msg; }
};
Derived(int j) try : Base(j) {
// Constructor body
cout << "This won't print" << endl;
} catch(BaseExcept&) {
throw DerivedExcept("Base subobject threw");;
}
};
int main() {
try {
Derived d(3);
} catch(Derived::DerivedExcept& d) {
cout << d.what() << endl; // "Base subobject threw"
}
getchar();
} ///:~
在Derived类的构造函数中,初始化列表处在关键字try和构造函数的函数体
之间。
如果构造函数发生异常,Derived类所包含的对象也就没有构造完成,因此
程序返回到创建该对象代码的地方是没有意义的
输出
Base subobject threw
C++允许在所有函数中使用函数级try块
//: C01:FunctionTryBlock.cpp {-bor}
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Function-level try blocks.
// {RunByHand} (Don't run automatically by the makefile)
#include <iostream>
using namespace std;
int main() try {
throw "main";
} catch(const char* msg) {
cout << msg << endl;
return 1;
getchar();
} ///:~
这种情况,catch块中的代码可以想函数体中的代码一样正常返回
输出
main
在vs里面会闪一下窗口 之后关闭