• 一次C++作业 try-throw-catch


    1、设计一个异常RangeError类响应输入的数不在指定范围内,实现并测试这个类。

    /*设计一个异常RangeError类响应输入的数不在指定范围内,实现并测试这个类。*/
    #include<iostream>
    #include<exception>
    using namespace std;
    
    class RangeError
    {
    public:
    	RangeError()
    	{
    		cout << "Please input a Integer Number(0~10000):";
    		int abc;
    		cin >> abc;
    		try
    		{
    			if (abc <= 10000 && abc >= 0)
    			{
    
    				cout << "Your Integer Number is:" << abc;
    			}
    			else
    			{
    				throw 1;
    			}
    		}
    		catch (int)
    		{
    			cout << "Your Integer Number is out";
    		}
    	}
    };
    int main()
    {
    	RangeError();
    }
    

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

    #include<iostream>
    using namespace std;
    class CException
    {
    public:
    	CException() {}
    	~CException() {}
    	const char* Reason() const
    	{
    		return "CException类中异常";
    		throw Reason();
    	}
    };
    void fn1()
    {
    	cout << "在子函数fn1()中触发CException类异常" << endl;
    	throw CException();
    }
    
    int main()
    {
    	cout << "进入主函数" << endl;
    	try
    	{
    		cout << "到达try模块中,即将调用子函数" << endl;
    		fn1();
    	}
    	catch (CException C)
    	{
    		cout << "在catch模块中,通过函数fn1(),捕获到CException类型异常,即将调用成员函数Reason()" << endl;
    		cout << C.Reason() << endl;
    	}
    	catch (char* str)
    	{
    		cout << "捕获到其他异常类型:" << str << endl;
    	}
    	cout << "回到主函数,异常已被处理。" << endl;
    }
    
  • 相关阅读:
    Thrift --- 支持双向通信
    Go -- 配置监控系统
    Go -- RPC 之 Thrift
    Go -- 一致性哈希算法
    Go -- runtime.Gosched()的作用分析
    Go -- import使用及. _的作用解析
    BNF 和 ABNF 扩充巴科斯范式 了解
    转 HTTP.SYS 详解
    转 HTTP/2: The Long-Awaited Sequel
    网站分析
  • 原文地址:https://www.cnblogs.com/xiaotian66/p/13257202.html
Copyright © 2020-2023  润新知