面向对象程序设计 第九章 模板和异常处理 异常处理

mac2025-12-25  6

1、异常处理 try、throw、catch关键字,联合使用

try { if(语句1) throw 数值1/"返回语句1"if(语句2) throw 数值2/"返回语句2"; } catch(int n)//用数值举例 { if(n==数值1) ... if(n==数值2) ... }

编写程序,说明错误信息的处理过程

#include<iostream> using namespace std; int main() { int month; cout<<"please input month:";cin>>month; try { if(month<1) throw 1; if(month>12) throw 2; } catch(int n) { if(n==1) cout<<"error:month is less than 1"<<endl; else if(n==2) cout<<"error:month is bigger than 12"<<endl; return 1; } cout<<"end"; return 0; } result: please input month:13 error:month is bigger than 12 please input month:0 error:month is less than 1 please input month:4 end

2、异常处理对象 编写程序说明异常处理对象的过程

#include<iostream> using namespace std; class unnomal//异常类的定义 { public: unnomal(){} char *getmessage() { return "error"; } }; void exthrow() { throw unnomal();//利用默认构造函数创建临时异常对象并强制抛出 } int main() { try { exthrow(); } catch(unnomal x) { cout<<x.getmessage()<<endl; } } result: error

编写程序,在异常类中定义带参数的构造函数,并利用该构造函数来处理不同的异常信息

#include<iostream> #include<string.h> using namespace std; class unnomal { char *x; public: unnomal(const char *s) { x=new char[strlen(s)+1]; strcpy(x,s); } char *getmessage() { return x; } }; void exthrow(int n) { if(n==1) throw unnomal("error1"); if(n==2) throw unnomal("error2"); } int main() { try { exthrow(1); } catch(unnomal x) { cout<<x.getmessage()<<endl; } try { exthrow(2); } catch(unnomal x) { cout<<x.getmessage()<<endl; } } result: error1 error2

注意: 在exthrow函数中抛出异常之前能够自动调用局部对象的析构函数进行处理。

3、异常处理中的构造与析构 编写程序,说明在抛出异常信息时,相关析构函数的自动调用过程

#include<iostream> using namespace std; class unnomal { public: unnomal(){} char *getmessage() { return "error"; } }; class test1 { public: test1() { cout<<"enter test1 constructor"<<endl; } ~test1() { cout<<"enter test1 destructor"<<endl; } }; class test2 { public: test2() { cout<<"enter test2 constructor"<<endl; } ~test2() { cout<<"enter test2 destructor"<<endl; } }; void exthrow() { test1 x; test2 y; cout<<"enter exthrow"<<endl; throw unnomal(); } int main() { cout<<"enter main"<<endl; try { exthrow(); } catch(unnomal p) { cout<<p.getmessage()<<endl; } } result: enter main enter test1 constructor enter test2 constructor enter exthrow enter test2 destructor enter test1 destructor error
最新回复(0)