C++语言基础 例程 异常处理的方法

贺老师的教学链接  本课讲解


例:防止除数为0

#include <iostream>
using namespace std;
template <typename T>
T Div(T x,T y)
{
    if(y==0)
        throw y;//抛出异常
    return x/y;
}


int main()
{
    int x=5,y=0;
    double x1=5.5,y1=0.0;
    try
    {
        //被检查的语句
        cout<<x<<"/"<<y<<"="<<Div(x,y)<<endl;
        cout<<x1<<"/"<<y1<<"="<<Div(x1,y1)<<endl;
    }
    catch(int)//异常类型
    {
        cout<<"除数为0,计算错误!"<<endl;//异常处理语句
    }
    catch(double)//异常类型
    {
        cout<<"除数为0.0,计算错误!"<<endl;//异常处理语句
    }
    return 0;
}


异常处理再例:求三角形周长
#include <iostream>
#include <stdexcept>
using namespace std;
int triangle(int a, int b, int c)
{
    if(a<0 || b<0 || c<0 || a+b<=c || a+c<=b || b+c<=a)
        throw runtime_error("The lengths of three sides can't form triangle");
    return a + b + c;
}


int main()
{
    int total = 0;
    try
    {
        total = triangle(3,4,7);
    }
    catch(const runtime_error& e)
    {
        cout<<e.what()<<endl;
    }
    cout<<total<<endl;
    return 0;
}


在异常处理中处理析构函数
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
    Student(int n,string nam):num(n), name(nam)
    {
        cout<<"constructor-"<<n<<endl;
    }
    ~Student( )
    {
        cout<<"destructor-"<<num<<endl;
    }
    void get_data( );
private:
    int num;
    string name;
};
void Student::get_data( )
{
    if(num==0)
        throw num; //如num=0,抛出int型变量num
    else
        cout<<num<<" "<<name<<endl;
    cout<<num<<" is in get_data()!"<<endl;
}


void fun( )
{
    Student stud1(1101,"Tan");
    stud1.get_data( );
    Student stud2(0,"Li");
    stud2.get_data( );
}


int main( )
{
    try
    {
        fun( );
    }
    catch(int n)
    {
        cout<<"num="<<n<<",error!"<<endl;
    }
    return 0;
}


在函数嵌套的情况下检测异常处理
#include <iostream>
using namespace std;
int main( )
{
    void f1( );
    try
    {
        f1( );   //调用f1( )
    }
    catch(double)
    {
        cout<<"OK0!"<<endl;
    }
    cout<<"end0"<<endl;
    return 0;
}
void f1( )
{
    void f2( );
    try
    {
        f2( );   //调用f2( )
    }
    catch(char)
    {
        cout<<"OK1!";
    }
    cout<<"end1"<<endl;
}
void f2( )
{
    void f3( );
    try
    {
        f3( );   //调用f3( )
    }
    catch(int)
    {
        cout<<"Ok2!"<<endl;
    }
    cout<<"end2"<<endl;
}
void f3( )
{
    double a=0;
    try
    {
        throw a;   //抛出double类型异常信息
    }
    catch(float)
    {
        cout<<"OK3!"<<endl;
    }
    cout<<"end3"<<endl;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迂者-贺利坚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值