异常处理

来源:互联网 发布:dota2手机直播软件 编辑:程序博客网 时间:2024/06/05 19:48

异常处理的基本思想:

若有异常则通过throw操作创建一个异常对象并抛掷。
将可能抛出异常的程序段嵌在try块之中。控制通过正常的顺序执行到达try语句,然后执行try块内的保护段。
如果在保护段执行期间没有引起异常,那么跟在try块后的catch子句就不执行。程序从try块后跟随的最后一个catch子句后面的语句继续执行下去。
catch子句按其在try块后出现的顺序被检查。匹配的catch子句将捕获并处理异常(或继续抛掷异常)。
如果匹配的处理器未找到,则运行函数terminate将被自动调用,其缺省功能是调用abort终止程序。




#include "stdafx.h"
#include <iostream>
#include <string>
#include <exception>
using namespace std;


class MyException {
private:
 string message;

public:
 MyException(const string & message): message(message) {}
 ~MyException() {}
 const string & getMessage() const { return message; }
};

class Demo {
public:
 Demo() { cout<<"Constructor of Demo"<<endl; }
 ~Demo() { cout<<"Destructor of Demo"<<endl; }
};

void func() throw(MyException) {                       //表明函数只能够抛掷类型MyException
 Demo d;
 cout<<"Throw MyException in func()"<<endl;
 throw MyException("exception thrown by func");     //throw      栈的解旋
}


int main() {
 cout<<"In main function"<<endl;
 try {                                              //try 复合语句
  func();
  cout<<"NEXT"<<endl;
 }
 catch(MyException & e) {                           //catch (异常声明) 复合语句
  cout<<"Caught an exception: "<<e.getMessage()<<endl;
 }

 cout<<"Resume the execution of main()"<<endl;

 system("pause");
 return 0;
}



0 0
原创粉丝点击