C、C++异常处理区别;

  1. C异常(C structured exception)只能处理一种类型(unsigned int),C++异常(C++ exception)处理很多类型。C异常根据无符号整型的值来标识,而C++异常是根据数据类型来标识的。当在C程序中引发了异常后,每一个能处理者都去检查异常内容来决定是自己处理还是交给其他处理者,或者是忽略。在C++程序中异常被抛出后,它有可能是任何一种类型。
  2. C异常处理模式是“异步”,当异常发生后会向下继续执行的。C++异常处理模式是“同步”,异常发生时就是异常抛出时!

在C++程序中引发C异常后,能被C的结构化异常者处理或者被C++ catch中的处理者处理。

下面这例子:在C++程序引发了C的异常。

// exceptions_Exception_Handling_Differences.cpp
// compile with: /EHa
#include <iostream>

using namespace std;
void SEHFunc( void );

int main() {
   try {
      SEHFunc();
   }
   catch( ... ) {
      cout << "Caught a C exception."<< endl;
   }
}

void SEHFunc() {
   __try {
      int x, y = 0;
      x = 5 / y;
   }
   __finally {
      cout << "In finally." << endl;
   }
}
程序结果:

In finally.
Caught a C exception.

下面这个例子是如何将C异常包装成C++异常

// exceptions_Exception_Handling_Differences3.cpp
// compile with: /EHa
#include <stdio.h>
#include <eh.h>
#include <windows.h>

class SE_Exception {
private:
   SE_Exception() {}
   unsigned int nSE;

public:
   SE_Exception( SE_Exception& e) : nSE(e.nSE) {}
   SE_Exception(unsigned int n) : nSE(n) {}
   ~SE_Exception() {}
   unsigned int getSeNumber() { return nSE; }
};

void SEFunc() {
   __try {
      int x, y = 0;
      x = 5 / y;
    }
    __finally {
      printf_s( "In finally\n" );
   }
}

void trans_func( unsigned int u, _EXCEPTION_POINTERS* pExp ) {
   printf_s( "In trans_func.\n" );
   throw SE_Exception( u );
}

int main() {
   _set_se_translator( trans_func );
    try {
      SEFunc();
    }
    catch( SE_Exception e ) {
      printf_s( "Caught a __try exception with SE_Exception.\n" );
      printf_s( "nSE = 0x%x\n", e.getSeNumber() );
    }
}

程序结果:

In trans_func.
In finally
Caught a __try exception with SE_Exception.
nSE = 0xc0000094

综上,C异常仅能被try{}catch(...){}来捕获处理,但是并没有关于异常类型和内容的说明,为了异常更清楚,可以将C异常包装成C++异常(上述例子)。

MSDN相关解释



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值