C++_try_catch使用

1. try_catch

try {
    语句组
}
catch(异常类型) {
    异常处理代码
}

2. 举例

2.1 try_catch_throw例子

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int a;
    try{
        cin >> a;
        if(a > 10)
        {
            cout << "输入合格 a = " << a << endl;
        }else
        {
            throw a;
        }
    }catch(int res)
    {
        cout << "异常!!!输入值小于10 res = " << res << endl;
    }
    return 0;
}

输出结果:

[root@tianyiyi try_catch]# ./try_catch 
12
输入合格 a = 12
[root@tianyiyi try_catch]# ./try_catch 
3
异常!!!输入值小于10 res = 3

2.2 多个catch

#include <iostream>
#include <string>
using namespace std;
class Base{ };
class Derived: public Base{ };
int main(){
    try{
        throw Derived();  //抛出自己的异常类型,实际上是创建一个Derived类型的匿名对象
        cout<<"This statement will not be executed."<<endl;
    }catch(int){
        cout<<"Exception type: int"<<endl;
    }catch(char *){
        cout<<"Exception type: cahr *"<<endl;
    }catch(Derived){
        cout<<"Exception type: Derived"<<endl;
    }
    return 0;
}

输出结果

[root@tianyiyi try_catch]# ./try_catch 
Exception type: Derived

2.3 嵌套的try_catch

#include <iostream>
#include <string>
using namespace std;

void fun()
{
    int a = 1;
    try
    {
        cout << "fun try block" << endl;
        throw -1;
    }
    catch(int ans)
    {
        cout << "fun throw ans = " << ans << endl;
    }
    
}

int main()
{
    int a;
    try{
        fun();
        cout << "main try block" << endl;

    }catch(int ans)
    {
        cout << "main throw ans = " << ans << endl;
    }
    return 0;
}

输出结果

从输出结果知晓,异常不会跨级抛出

[root@tianyiyi try_catch]# ./try_catch 
fun try block
fun throw ans = -1
main try block

3. 和if_else的区别

  1. if_else是流程控制语句,try_catch是异常处理语句。

4. throw在C++函数中的应用

static int fun1(int arg1,int arg2) throw();				// 表示该函数不会抛出异常
static int fun1(int arg1,int arg2) throw(...);			// 表示该函数可能会抛出各种类型的异常
static int fun1(int arg1,int arg2) throw(int);			// 表示该函数会抛出int类型的异常
  • 5
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

fantongl

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

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

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

打赏作者

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

抵扣说明:

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

余额充值