码迷,mamicode.com
首页 > 其他好文 > 详细

异常处理

时间:2019-08-23 00:32:07      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:测试   bsp   stream   null   fun   space   ash   检查   使用   

异常机制 计算机计算的时候遇到除法 除数都是0的情况

     文件打开失败

     申请对内存的时候失败

异常运行的时候遇到的问题 不是代码的问题

             c语言通过返回值做异常处理

             异常遇到之后 提交给调用方进行

处理方式 try 测试代码

    catch捕获异常

    throw抛出异常

有遇到异常直接利用throw进行抛出 交给外部的catch进行捕获 如果处理不了或者捕获不到交给上级

往上级的try里面找 如果依然找不到 调用abort中断这个程序

举出一些异常的例子:

fopen 文件打开失败 能否在fopen里处理这个异常

标准异常类  exception

bad_alloc new内存申请太多 导致申请失败

out_of_range 越界string字符串越界

typeid 可以得到类型

在多态中 父类执政如果指向null 使用typeid就汇报 bad_typeid

 1 #include<iostream>
 2 
 3 
 4 using namespace std;
 5 //文件对象  fstream+成员函数
 6 //c语言  文件指针+函数
 7 
 8 void fun(int x, int y)
 9 {
10     if (y == 0)
11     {
12         throw"被除数为0";    //throw后面的异常可以是任意类型
13     }
14     cout << x / y << endl;
15 }
16 int main()
17 {
18     float num;
19     cout << typeid(num).name() << endl;
20 //如果表达式的类型是类类型且至少包含有一个虚函数,则typeid操作符返回表达式的动态类型,需要在运行时计算;否则,typeid操作符返回表达式的静态类型,在编译时就可以计算
21     /*
22     int *p=new int[0xfffffff];
23     int *p1=new int[0xfffffff]; bad_alloc内存申请过多异常
24     int *p2=new int[0xfffffff];
25     int *p3=new int[0xfffffff];
26     delete[] p;
27     delete[] p1;
28     delete[] p2;
29     delete[] p3;
30 
31     string str("hello");
32     str.at(8);out_off_range 越界—(c没有越界检查)
33     
34     */
35     int x, y;
36     try
37     {
38         //求两个数字相除
39         cin >> x >> y;
40         fun(x, y);
41     }
42     catch (int x)//捕获int类型的异常
43     {
44 
45     }
46     catch (char x)//捕获char类型的异常
47     {
48 
49     }
50     catch (char* str)//捕获字符串类型的异常
51     {
52         cout << str << endl;
53         cout << "请重新输入" << endl;
54         cin >> y;
55         fun(x,y);
56     }
57     catch (...)//捕获任意类型的异常
58     {
59 
60     }
61 }

 

异常处理

标签:测试   bsp   stream   null   fun   space   ash   检查   使用   

原文地址:https://www.cnblogs.com/liugangjiayou/p/11397406.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!