您的位置:首页 > 其它

How to handle exception in managed code and unmanaged code

2015-12-12 23:55 645 查看
As we known, try...catch mechanism is a quite common feature for the high level languages like java or C#. Although C++ proclaimed that it supports this mechanism, the memory management limitation of C++ makes this try...catch function is weak.C++ cannot automatically captures the exception like C# or Java, so in case of exception happens, we must throw explicitly.
// exceptions#include <iostream>usingnamespace[code] std;
int
main() {
Char* pEx = 0;
...
try[code]  {
if(pEx == 0)
throw
20;  }
catch
(
int
e)  {    cout <<
"An exception occurred. Exception Nr. "
<< e <<
'\n'
;  }
return[code] 0;
}
But if we are coding with managed and unmanaged code, how to handle the exception?Actually for the managed part try block no doubt can capture the exception, for the un managed part we can use one special way.Try catching using the ExternalException classThe base exception type for all COM interop exceptions and structured exception handling(SEH) exceptions.
[SerializableAttribute][ComVisibleAttribute(true)]
public ref class ExternalException : public SystemException
As the sample above, makes your target clause derived from ExternalException class, then internally the function can capture the exception.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: