1-3 捕获异常

1.3 捕获异常

1.3.1 try块与exception handler

如果需要捕获异常,会依次执行到第一个符合的,然后退出该块。

try
{
}
catch (type1 id1)
{
}
catch (type2 id2)
{
}
catch (type3 id3)
{
}

1.3.2 修改setjmp案例(异常处理代替)

保证了程序流程正常,并保证了析构函数的调用。

#include <iostream>
using namespace std;

class Rainbow
{
public:
Rainbow() { cout << "Rainbow()" << endl; }
~Rainbow() { cout << "~Rainbow()" << endl; }
};

void oz()
{
Rainbow rb;
for (int i = 0; i < 3; i++)
cout << "There is no place like home" << endl;
throw 47;
}

int main()
{
try
{
cout << "tornado, switch, munchins..." << endl;
oz();
}
catch (int)
{
cout << "Auntie Em!"
<< "I had the strangest dream..."
<< endl;
}
return 0;
}

/*output:
tornado, switch, munchins...
Rainbow()
There is no place like home
There is no place like home
There is no place like home
~Rainbow()
Auntie Em!I had the strangest dream...
*/

1.3.3 终止与恢复

异常处理中,存在两种模型:终止模型和恢复模型

终止模型:不可能在发生异常的地方恢复程序,直接终止

恢复模型:将try块放入while里,但是工程中没多大用。