Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you catch a native exception in C# code?

Tags:

c#

.net

exception

In C# code can you catch a native exception thrown from deep in some unmanaged library? If so do you need to do anything differently to catch it or does a standard try...catch get it?

like image 454
Matt Avatar asked Sep 29 '08 20:09

Matt


People also ask

Can you catch exceptions in C?

C itself doesn't support exceptions but you can simulate them to a degree with setjmp and longjmp calls.

Why we should not catch exception?

Because when you catch exception you're supposed to handle it properly. And you cannot expect to handle all kind of exceptions in your code. Also when you catch all exceptions, you may get an exception that cannot deal with and prevent code that is upper in the stack to handle it properly.

Does C# have try catch?

The try-catch statement in C# is used in exceptions in C#. The try block holds the suspected code that may get exceptions. When an exception is thrown, the . NET CLR checks the catch block and checks if the exception is handled.


2 Answers

You can use Win32Exception and use its NativeErrorCode property to handle it appropriately.

// http://support.microsoft.com/kb/186550 const int ERROR_FILE_NOT_FOUND = 2; const int ERROR_ACCESS_DENIED = 5; const int ERROR_NO_APP_ASSOCIATED = 1155;   void OpenFile(string filePath) {     Process process = new Process();      try     {         // Calls native application registered for the file type         // This may throw native exception         process.StartInfo.FileName = filePath;         process.StartInfo.Verb = "Open";         process.StartInfo.CreateNoWindow = true;         process.Start();     }     catch (Win32Exception e)     {         if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND ||              e.NativeErrorCode == ERROR_ACCESS_DENIED ||             e.NativeErrorCode == ERROR_NO_APP_ASSOCIATED)         {             MessageBox.Show(this, e.Message, "Error",                      MessageBoxButtons.OK,                      MessageBoxIcon.Exclamation);         }     } } 
like image 78
Vivek Avatar answered Sep 30 '22 03:09

Vivek


Catch without () will catch non-CLS compliant exceptions including native exceptions.

try {  } catch {  } 

See the following FxCop rule for more info http://msdn.microsoft.com/en-gb/bb264489.aspx

like image 39
trampster Avatar answered Sep 30 '22 04:09

trampster