异常
当程序检测到一个它无法处理的问题就需要用到异常处理。检测出问题的部分应该发出某种信号表示程序碰到了故障,信号发出方无需知道故障将在何处解决。
try
{
//程序中抛出异常
throw value;
}
catch(valuetype1 v)
{
//例外处理程序段
}
catch(valuetype2 v)
{
//例外处理程序段
}
throw抛出值,catch接受
异常执行流程
1、执行try语句块的保护段
2、如果保护段执行期间没有异常,跟在try语句后面的catch子句就不会执行,从最后一个catch后跟随的语句执行下去
3、如果有异常被throw,按照顺序检查catch类型。
4、没有找到匹配的处理器,运行terminate函数,调用abort终止程序
5、找到匹配的处理器,捕获值,创建异常对象,一旦程序开始执行异常处理代码,沿着函数调用链创建的对象(调用析构函数)将被销毁。
#includeusing namespace std;int main(){ char myarray[10]; try { for (int n=0; n<=10; n++) { if (n>9) throw "Out of range"; myarray[n]='z'; } } catch (const char * str) { cout << "Exception: " << str << endl; } try { throw 1; throw "error"; } catch(char *str) { cout << str << endl; } catch(int i) { cout << i << endl; } return 0;}
程序输出为:
Exception: Out of range
1
C++标准库的异常类层次结构
C++标准库中的异常层次的根类被称为exception,定义在库的头文件<exception>中
exception类的接口
namespace std //注意在名字空间域std中{ class exception { public: exception() throw() ; //默认构造函数 exception(const exception &) throw() ; //复制构造函数 exception &operator=(const exception&) throw() ; //复制赋值操作符 virtual ~exception() throw() ; //析构函数 virtual const char* what() const throw() ; //返回一个C风格的字符串,目的是为抛出的异常提供文本描述 };}
<stdexcept>
Exception classes
This header defines a set of standard exceptions that both the library and programs can use to report common errors.
They are divided in two sets:Logic errors
:逻辑错误
:参数的结果值不存在
:不合适的参数
:试图生成一个超过此类型的最长对象
:使用一个超过 有效范围的值
Runtime errors
:运行时错误
:生成的结果超出了有意义的值域范围
:计算上溢
:计算下溢
对整数,溢出指代数值:小于最小值为下溢,大于最大值为上溢
对浮点数,溢出指绝对值:绝对值小于浮点数所能表示的最小值,为下溢,当作 0;绝对值大于浮点数所能表示的最大范围,为上溢,当作 INF
根据具体符号的不同,又分为:正上溢、正下溢、负上溢、负下溢
自己定义异常类
#include#include using namespace std;//可以自己定义Exceptionclass myexception: public exception{ virtual const char* what() const throw() { return "My exception happened"; }}myex;int main () { try { if(true) //如果,则抛出异常; throw myex; } catch (exception& e) { cout << e.what() << endl; } return 0;}
继承exception覆盖what函数
程序输出
My exception happened
参考:
异常处理后还能继续运行之后的代码吗?
一个异常没有被捕获,它将终止当前的程序,如果被捕获了,则从最后一个catch后面的第一条语句开始继续执行
#includeusing namespace std;int div(int x, int y){ if(y==0) throw 0; return x/y;}int main(){ int m,n; try { cout<<"please input two numbers :"< >m>>n; cout<<"m/n is "< <<<"0 is unsuccessful"<
如果cout<<1/0;系统将终止,如果放在异常处理块中,还能继续运行
捕获所有异常
#includeusing namespace std;void f(int);void f(int x){ try { if(x>0) { throw 0; } if(x==0) { throw 'a'; } if(x<0) { throw 1.1; } } catch(int) { cout<<"x>0"<
output
x>0
unknown error!
unknown error!