Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Exception Error Code in C#

Tags:

c#

exception

try {      object result = processClass.InvokeMethod("Create", methodArgs); } catch (Exception e) {       // Here I was hoping to get an error code. } 

When I invoke the above WMI method I am expected to get Access Denied. In my catch block I want to make sure that the exception raised was indeed for Access Denied. Is there a way I can get the error code for it ? Win32 error code for Acceess Denied is 5. I dont want to search the error message for denied string or anything like that.

Thanks

like image 677
Frank Q. Avatar asked Aug 01 '11 00:08

Frank Q.


People also ask

How do you handle exception in C?

As such, C programming does not provide direct support for error handling but being a system programming language, it provides you access at lower level in the form of return values. Most of the C or even Unix function calls return -1 or NULL in case of any error and set an error code errno.

Can we handle exception in C?

C doesn't support exception handling.


1 Answers

You can use this to check the exception and the inner exception for a Win32Exception derived exception.

catch (Exception e) {       var w32ex = e as Win32Exception;     if(w32ex == null) {         w32ex = e.InnerException as Win32Exception;     }         if(w32ex != null) {         int code =  w32ex.ErrorCode;         // do stuff     }         // do other stuff    } 

Starting with C# 6, when can be used in a catch statement to specify a condition that must be true for the handler for a specific exception to execute.

catch (Win32Exception ex) when (ex.InnerException is Win32Exception) {     var w32ex = (Win32Exception)ex.InnerException;     var code =  w32ex.ErrorCode; } 

As in the comments, you really need to see what exception is actually being thrown to understand what you can do, and in which case a specific catch is preferred over just catching Exception. Something like:

  catch (BlahBlahException ex) {         // do stuff      } 

Also System.Exception has a HRESULT

 catch (Exception ex) {        var code = ex.HResult;  } 

However, it's only available from .NET 4.5 upwards.

like image 148
Preet Sangha Avatar answered Oct 04 '22 01:10

Preet Sangha