异常的处理方法

#if  0
int func()
{
    //...
    FILE* pfile;
    if (!(pfile = fopen("null", "r")))
    {
        //...
        cout << "文件打开失败" << endl;
        return -1;
    }
    return 0;
}
int func2()
{
    if (-1 == func())
    {
        //错误处理
    }
}
int main()//缺点 逐层判断  优点 层次清晰
{
    if (-1 == func2())
    {
        //...返回值带错误
    }
    return 0;
}
#endif//利用返回值
#if 0
#include<setjmp.h>
jmp_buf j_err;
void func3()
{
    //...
    FILE* pFile;
    if (!(pFile = fopen("null", "r")))
    {
        //...
        cout << "调用longjmp前" << endl;
        longjmp(j_err, -1);
        cout << "调用longkmp后" << endl;
    }
}
void func4()
{
    cout << "调用func3前" << endl;
    func3();
    cout << "调用func3后" << endl;
}
int main()
{
    if (setjmp(j_err) == 0)//j_err默认0
    {
        cout << "第一次调用setjmp" << endl;
        func4();
    }
    else
    {
        cout << "第二次调用setjmp" << endl;
    }
    return 0;
}
#endif // setjmp  longjmp
#if 0
void func()
{
    FILE* pFile;
    if (!(pFile = fopen("null","r")))
    {
        //...
        throw - 1;
    }
    char* p = (char*)malloc(0x123213);
    if(!p)
    {
        throw "内存分配失败";
    }
}
int main()
{
    try
    {
        func();
    }
    catch (int ex)
    {
        if (-1 == ex)
        {
            cout << "文件打开失败\n";
            return -1;
        }
    }
    catch (const char* ex)
    {
            cout << ex<< endl;
    }
    return 0;
}
#endif // 抛出 捕获异常
#if 0
class A
{};
class :public A 
{};
int main()
{
    try
    {
        throw B();//抛出B类型异常
    }
    catch (A& ex) //被A捕获 根据异常类型从上到下匹配 而非优先匹配
        //因此对子类类型异常的捕获不要放在对基类类型异常捕获的后面
    {
        cout << "A异常" << endl;
    }
    catch (B& ex)//用引用来接 ex就是异常   不用就是异常的拷贝
    {
        cout << "B异常" << endl;
    }
    return 0;
}
#endif//捕获顺序
#if 0
class OverFlow :public exception
{
//...
    const char* what()const throw()
    {
        return "堆栈饱满";
    }
};
void push(int data)
{
    //...
    //throw overflow_error("堆栈上溢");
    throw OverFlow();
}
int main()
{
    try 
    {
        push(10);
    }
    catch (exception& ex)//异常的基类 exception
    {
        cout << ex.what() << endl;
    }
    return 0;
}
#endif // 标准异常库

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值