简体   繁体   English

.Net 4.0和.Net 2.0中的异常代码更改

[英]Exception Code Changes in .Net 4.0 and .Net 2.0

I am migrating my .Net Framework 2.0 Application to .Net Framework 4.0. 我正在将.Net Framework 2.0应用程序迁移到.Net Framework 4.0。

In that I am having a program to get Exception Code when an Exception raised. 这样,我有一个程序在引发异常时获取异常代码。 But unfortunately the Exception code varies between .Net Framework 2.0 and .Net Framework 4.0. 但是不幸的是,.NET Framework 2.0和.Net Framework 4.0之间的异常代码有所不同。 Below is my Code 下面是我的代码

try
{
       throw new DirectoryNotFoundException();
}
catch (Exception ex)
{
        MessageBox.Show(Marshal.GetExceptionCode().ToString());
}

The above program return "-532459699" for .Net Framework 2.0, and it return "-532462766" for .Net Framework 4.0 上面的程序对于.Net Framework 2.0返回“ -532459699”,对于.Net Framework 4.0返回“ -532462766”

Is there any way to get the exception code as same as .Net Framework 2.0? 有没有办法获得与.Net Framework 2.0相同的异常代码?

That is not for managed exception handling. 这不适用于托管异常处理。 If you look at the description of the Marshal class it makes that pretty clear: 如果您看一下Marshal课程的描述,那就很清楚了:

Provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks, and converting managed to unmanaged types, as well as other miscellaneous methods used when interacting with unmanaged code. 提供了用于分配非托管内存,复制非托管内存块以及将托管类型转换为非托管类型的方法的集合,以及与非托管代码进行交互时使用的其他方法。

Why are you getting different codes then? 那为什么要得到不同的密码? It's actually not worth discussing because that exception code isn't coming from your managed application. 实际上,这不值得讨论,因为该异常代码不是来自托管应用程序。 The importance is the right way to handle it would be like this: 重要性是正确的处理方式,如下所示:

try { }
catch (DirectoryNotFoundException ex) { }

and now you know that was the exception that was thrown. 现在您知道那是抛出的异常。

The answer to your implied question "Why are these codes different?" 您的隐含问题“为什么这些代码不同?”的答案 is "You shouldn't care, that's an implementation detail" . “您不必关心,这是一个实现细节”

If your actual question is "How can I identify an exception?" 如果您的实际问题是“如何识别异常?” , see How to get Exception Error Code in C# . 请参阅如何在C#中获取异常错误代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM