一种是直接调用abort(),中断程序,不够灵活
另一种用try,catch的形式
即,
try{
...
if() throw ...
}
catch(Type){
...
}
catch(Type1){
...
}
..
catch(...){
...
}
多个catch捕获try模块的throw后的内容
具体来说,函数遇到throw,就会终端try模块的运行,根据throw的类型向下匹配catch内容,然后再catch之后执行,最后一个catch表示任何类型。没有遇到throw就try部分执行完了,跳过catch
对于函数部分的行为是,throw出的类型一路向下找catch,找不到就跳出函数再找,一层层,直到main也找不不到就一般默认调用abort()退出。
下面例子
#include <iostream>
#include <stdlib.h>
using namespace std;
double division(int a, int b)
{
if( b == 0 )
{
// cout<<"input err"<<endl;
//abort();
throw "Division by zero condition!";
}
return (a/b);
}
int Fun(int a,int b){
return division(a,b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
while(1){
cout<<"input x y to figure out x/y\n";
cin>>x>>y;
try {
z = Fun(x, y);
cout << z << endl;
}
catch (const char * msg) {
cerr << msg << endl;
}
}
return 0;
}
运行结果如下
此外,C++提供了stdexcept头文件提供了一些异常类
exception | 最常见的问题 |
runtime_error | 只有在运行时才能检测出的问题 |
range_error | 运行时错误:生成的结果超出了有意义的值域范围 |
overflow_error | 运行时错误:计算上溢 |
underflow_error | 运行时错误:计算下溢 |
logic_error | 程序逻辑错误 |
domain_error | 逻辑错误:参数对应的结果值不存在 |
invalid_argument | 逻辑错误:参数无效 |
length_error | 逻辑错误:试图创建一个超过该类型最大长度的对象 |
out_of_range | 逻辑错误:使用一个超出有效范围的值 |
异常类只定义了一个名为what的成员函数,该函数没有任何参数,返回值是一个指向C风格字符串的const char*
以上的exception是一个基类,runtime_error与logic_error由它继承而来,接收string对象作为参数,提供what方法返回字符数据
以上代码可以改成
#include <iostream>
#include <stdlib.h>
#include <stdexcept>
using namespace std;
double division(int a, int b)
{
if( b == 0 )
{
// cout<<"input err"<<endl;
//abort();
//throw "Division by zero condition!";
throw exception();//exception异常基类
// throw runtime_error("y can't be 0");//runtime_error异常类
}
return (a/b);
}
int Fun(int a,int b){
return division(a,b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
while(1){
cout<<"input x y to figure out x/y\n";
cin>>x>>y;
try {
z = Fun(x, y);
cout << z << endl;
}
catch (const char * msg) {//依次捕获几个类的异常
cerr << msg << endl;
}
catch (const exception & err) {
cerr << err.what() << endl;
}
catch (const runtime_error & err) {
cerr << err.what() << endl;
}
}
return 0;
}
分别抛出exception基类异常与runtime_error异常