首页 > 编程语言 > 详细

C++里的异常处理

时间:2019-12-22 13:31:31      阅读:93      评论:0      收藏:0      [点我收藏+]
  • 实验环境 win7 下的vs2017,基本原则:throw抛出的数据类型,和cathc语句的数据类型要一致
  • 异常的引发和异常的处理可以分布在不同函数中,所以c++的异常是跨栈的
  • 异常是由“地地道道“的错误所引发
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<string.h>
using namespace std;

void testerror(int x,int y)
{

    if (y==0)
    {
        throw x;
    }
    cout << "计算结果:"<<x/y<< endl;
}

void main()
{
    try
    {
        testerror(100,0);
    }
    catch (int x)
    {
        cout  << x << "不能被0整除" << endl;
    }
    catch (...)
    {
        cout << "无言的结局" << endl;
    }
    system("pause");
}
  • 下面的例子揭示了throw语句的强大,无论多少层都会抛出错误
void testerror(int x,int y)
{

    if (y==0)
    {
        throw x;
    }
    cout << "计算结果:"<<x/y<< endl;
}

void awrap()
{
    testerror(100, 0);
}

void main()
{
    //
    try
    {
        awrap();
    }
    catch (int x)
    {
        cout  << x << "不能被0整除" << endl;
    }
    catch (...)
    {
        cout << "无言的结局" << endl;
    }
    system("pause");
}

输出结果:

技术分享图片

 

  •  这种异常的抛出和定义方法并不能如愿以偿的解决自定义异常
void testerror(char * name)
{
    cout << "his name is " << name << endl;
    if (name=="雨化田")
    {
        throw name;
    }
    cout << "原来是:"<<name<<"!快快进来享用广式炒面"<< endl;
}

int main()
{
    //
    char name[] = "雨化田";
    char *hisname = name;
    try
    {
        testerror(hisname);
    }
    catch (char *name)
    {
        cout << "妈爷子诶~这不是:" << name << endl;
    }
    catch (...)
    {
        cout << "无言的结局" << endl;
    }
    system("pause");
    return 0;
}

输出结果:看来并未按照我们的意愿去处理

技术分享图片

C++里的异常处理

原文:https://www.cnblogs.com/saintdingspage/p/12079491.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!