0

I am migrating my .Net Framework 2.0 Application to .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. 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

Is there any way to get the exception code as same as .Net Framework 2.0?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • Does Marshal.GetExceptionCode even work for normal managed exceptions? – Dirk Sep 24 '14 at 11:59
  • In the remarks section on MSDN is says: `GetExceptionCode is exposed for compiler support of structured exception handling (SEH) only` – Magnus Sep 24 '14 at 12:03
  • You are seeing too different exceptions, see http://stackoverflow.com/a/9164144/426894 and http://stackoverflow.com/a/19919001/426894 – asawyer Sep 24 '14 at 12:05

2 Answers2

2

That is not for managed exception handling. If you look at the description of the Marshal class it makes that pretty clear:

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.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
1

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#.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272