首页 > 试题广场 >

定义一个异常类 CException,有成员函数 Reaso

[问答题]

定义一个异常类 CException,有成员函数 Reason(),用来显示异常的类型,定义函 数 fn1()触发异常,在主函数的 try 模块中调用 fn1(),catch 模块中捕获异常,观察程序的执行流程。

推荐

解:

#include <iostream.h> class CException { public: CException(){}; ~CException(){}; const char *Reason() const { return "CException 类中的异常。"; } }; void fn1() { cout<< "在子函数中触发 CException 类异常" << endl; throw CException(); } void main() { cout << "进入主函数" << endl; try { cout << " try 模块中,调用子函数" << endl; fn1(); } catch( CException E ) { cout << " catch 模块中,捕获到 CException 类型异常:"; cout << E.Reason() << endl; } catch( char *str ) { cout << "捕获到其它类型异常:" << str << endl; } cout << "回到主函数,异常已被处理" << endl; }

程序运行输出:

进入主函数

try 模块中,调用子函数

在子函数中触发 CException 类异常

catch 模块中,捕获到 CException 类型异常:CException 类中的异常。

回到主函数,异常已被处理


发表于 2018-04-18 20:32:14 回复(0)