C++异常

我们在处理异常有不同的方式:

在C语言中我们可以利用参数的值,来判断是否执行成功或是否有异常情况,如下面简单的代码示例:

#include <stdio.h>
#include <stdlib.h>

#define SIZE 1024

void getMemory(char** p)

{

    *p = (char*)malloc(SIZE);

}

int main()

{

    char* p = NULL;

    getMemory(&p);

    if(p != NULL)

    {

        //获取一块内存空间,可以使用这个内存块。

        //...
        delete p;

        p = NULL;

    }else
    {

        //获取内存失败,异常情况。

    }

    return 0;

}

当然我们也可以利用返回值来判断程序是否有异常,如malloc()函数就是根据返回值来判断函数执行是否有异常。

在C++我们通常根据返回值来判断程序是否产生错误异常,就不再举例,C++还提供try{}catch(){}来捕获异常,具体见下面例子:

#include <iostream>
#include <math.h>

double calculatorArea(double a, double b, double c)
{
    if((a+b>c) && (a+c>b) && (b+c>a))
    {
        double s = (a + b + c) / 2;
        return (sqrt(s * (s - a) * (s - b) * (s - c)));
    }else
    {
        throw(-1);
    }
}

int main(void)
{

    double a, b, c;
    while(1)
    {
        std::cout<<"请输入三角形的三边,以空格隔开。"<<std::endl;
        std::cin>>a>>b>>c;
        try
        {
            std::cout<<calculatorArea(a, b, c)<<std::endl;
        }catch(int e)
        {
            std::cout<<"e:"<<e<<std::endl;
        }
    }

    return 0;

}

注意上面throw()中的类型和catch()捕获的类型一定要相同,try{}catch(){}catch(){}一个try可以对应多个catch,以匹配throw()的类型,catch(...){//default},对应默认类型,以防没有匹配,程序中止运行。

现在请看下面两段程序:

1.

#include <iostream>

void g()
{
    try
    {
        throw((double)-1);
    }catch(int e)
    {
        std::cout<<"int:"<<e<<std::endl;
    }
    std::cout<<"end g()"<<std::endl;
}

void f()
{
    try
    {
        g();
    }catch(char e)
    {
        std::cout<<"char:"<<e<<std::endl;
    }
    std::cout<<"end f()"<<std::endl;
}



int main(void)
{
    try
    {
        f();
    }catch(double e)
    {
        std::cout<<"main double:"<<e<<std::endl;
    }
    std::cout<<"end main()"<<std::endl;

    return 0;

}

结果:

main double:-1

"end main()

2.

#include <iostream>

void g()
{
    try
    {
        throw((int)-1);
    }catch(int e)
    {
        std::cout<<"int:"<<e<<std::endl;
    }
    std::cout<<"end g()"<<std::endl;
}

void f()
{
    try
    {
        g();
    }catch(char e)
    {
        std::cout<<"char:"<<e<<std::endl;
    }
    std::cout<<"end f()"<<std::endl;
}



int main(void)
{
    try
    {
        f();
    }catch(double e)
    {
        std::cout<<"main double:"<<e<<std::endl;
    }
    std::cout<<"end main()"<<std::endl;

    return 0;

}
结果:

int:-1

end g()

end f()

end main()

说明程序抛出异常后,从本层向调用层抛异常,若不匹配,则该层代码不再执行,继续向上层抛异常。若匹配,则不再向上层抛异常执行catch(){}后面的代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值