c++(6) 异常
内容目录:
1.异常概念
2.异常处理
内容
1.异常概念
运行时错误是指程序在运行期间发生的错误,例如除数为 0、内存分配失败、数组越界、文件不存在等。C++ 异常(Exception)机制就是为解决运行时错误而引入的。
运行时错误如果放任不管,系统就会执行默认的操作,终止程序运行,也就是我们常说的程序崩溃(Crash)。C++ 提供了异常(Exception)机制,让我们能够捕获运行时错误,给程序一次“起死回生”的机会,或者至少告诉用户发生了什么再终止程序。
2.异常处理
1.异常模版
try{ // 可能抛出异常的语句 }catch(exceptionType variable){ // 处理异常的语句 }
#include <iostream> #include <string> #include <exception> using namespace std; int main(){ string str = "http://c.biancheng.net"; try{ char ch1 = str[100];//不抛出异常 cout<<ch1<<endl; }catch(exception e){ cout<<"[1]out of bound!"<<endl; } try{ char ch2 = str.at(100);(由string 抛出异常) cout<<ch2<<endl; }catch(exception &e){ //exception类位于<exception>头文件中 cout<<"[2]out of bound!"<<endl; } return 0; }
2.异常抛出
throw关键字用来抛出一个异常,这个异常会被 try 检测到,进而被 catch 捕获。
3.异常类
catch(exceptionType variable)
exceptionType 异常类型
variable保持的异常信息
try抛出异常 由于catch接收 (这里可以多个catch)
所以异常的抛出需要由对应的异常来接收
try{ //可能抛出异常的语句 }catch (exception_type_1 e){ //处理异常的语句 }catch (exception_type_2 e){ //处理异常的语句 } //其他的catch catch (exception_type_n e){ //处理异常的语句 }
4.异常接口声明
在函数前 void test() throw(){函数体}
1.函数体throw -1 不能抛出任何异常
2.抛出个别异常 int ,float char
3. 抛出任何异常
5.栈解旋
异常被抛出后,从进入try块起,到异常被抛掷前,这期间在栈上构造的所有对象,都会被自动析构。析构的顺序与构造的顺序相反,这一过程称为栈的解旋(unwinding).
6.异常的声明周期
7.异常的多态
8.编写自己的异常类