经验分享,如何使用try,catch, throw之二

本文探讨了在软件开发中如何合理地使用try-catch-throw进行异常处理。提出了在不同访问级别的函数中应用这些机制的具体建议,并通过代码示例对比了不当与推荐的做法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 什么时候使用try,catch,什么时候不用;什么时候用throw,什么时候不用。工作了很多年才明白。

我个人的理解是:
1。在private或者protected的成员函数不使用try,catch,而只使用throw
2。如果在private或者protected的成员函数需要使用try,catch,那么就要使用rethrow
3。在public成员函数里使用try,catch
4。如果该类相对于整个项目来说是属于被调用层,那么public成员函数也可以不使用try,catch
5。如果调用第三方的代码,我一般都会用try,catch

我个人的习惯是把private或者protected成员函数的名字使用前缀__,public函数不用

先看一个我不喜欢的写法
//------------- try, catch, throw 例子,不喜欢的写法 ------------
class CTest
{
public:
  int Init();
private:
  int __InitA();
  int __InitB();
  int __InitC();
}

//--------- Init ------------
int CTest:Init()
{
  try
  {
    int err;
    err = __InitA();
    if (err != 1)
        throw -1;

    err = __InitB();
    if (err != 1)
        throw -2;

    err = __InitC();
    if (err != 1)
        throw 3;

    return 1;
  }
  catch(int & err)
  {
    return err;
  }
}

//---------- __InitA ----------
int CTest::__InitA()
{
  try
  {
    int err;
    err = DoSomething1();
    if (err != 1)
        throw -1;

    err = DoSomething2();
    if (err != 1)
        throw -2;
     
    return 1;
  }
  catch(int & err)
  {
    return err;
  }
}

__InitB, ___InitC和___InitA类似

下面是我个人比较喜欢的写法

//------------- try, catch, throw 例子,喜欢的写法 ------------
class CTest
{
public:
  int Init();
private:
  int __InitA();
  int __InitB();
  int __InitC();
}

//--------- Init ------------
int CTest:Init()
{
  try
  {
    __InitA();
    __InitB();
    __InitC();

    return 1;
  }
  catch(int & err)
  {
    return err;
  }
}

//---------- __InitA ----------
int CTest::__InitA()
{
    int err;
    err = DoSomething1();
    if (err != 1)
        throw -1;

    err = DoSomething2();
    if (err != 1)
        throw -2;
     
    return 1;
}

__InitB, ___InitC和___InitA类似
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值