How to get Exception Error Code in C#

c# exception error code list
custom exception handling in c# with example
c# ignore exception and continue
application exception in c#
throw exception c#
c# exception handling best practices
c# catch multiple exceptions
c# exception message
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

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.

C# Exception Handling Best Practices, Exceptions are a type of error that occurs during the execution of an application. Your exception handling code can utilize multiple C# catch  try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks. It is followed by one or more catch blocks. catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem.

You should look at the members of the thrown exception, particularly .Message and .InnerException.

I would also see whether or not the documentation for InvokeMethod tells you whether it throws some more specialized Exception class than Exception - such as the Win32Exception suggested by @Preet. Catching and just looking at the Exception base class may not be particularly useful.

Best Practices for exceptions, Hai,. Try Throw New ArgumentNullException("") Catch ex As Exception MsgBox(​Err.Number) End Try. in vb.net using "Err.Number" we can get  C# exception handling is done with the follow keywords: try, catch, finally, and throw try – A try block is used to encapsulate a region of code. If any code throws an exception within that try block, the exception will be handled by the corresponding catch. catch – When an exception occurs, the Catch block of code is executed.

Building on Preet Sangha's solution, the following should safely cover the scenario where you're working with a large solution with the potential for several Inner Exceptions.

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

...

private bool ExceptionContainsErrorCode(Exception e, int ErrorCode)
{
    Win32Exception winEx = e as Win32Exception;
    if (winEx != null && ErrorCode == winEx.ErrorCode) 
        return true;

    if (e.InnerException != null) 
        return ExceptionContainsErrorCode(e.InnerException, ErrorCode);

    return false;
}

This code has been unit tested.

I won't harp too much on the need for coming to appreciate and implement good practice when it comes to Exception Handling by managing each expected Exception Type within their own blocks.

Exception Class (System), I want to have this structure in my code but when i get a exception i need the error code of the exception, but i think that´s not possivel, anyone  The C# language's exception handling features help you deal with any unexpected or exceptional situations that occur when a program is running. Exception handling uses the try , catch , and finally keywords to try actions that may not succeed, to handle failures when you decide that it is reasonable to do so, and to clean up resources afterward.

I suggest you to use Message Properte from The Exception Object Like below code

try
{
 object result = processClass.InvokeMethod("Create", methodArgs);
}
catch (Exception e)
{  
    //use Console.Write(e.Message); from Console Application 
    //and use MessageBox.Show(e.Message); from WindowsForm and WPF Application
}

How to Get Error Number in C# - MSDN, Here, you will learn about exception handling in C# using try, catch, and finally blocks. try { // put the code here that may raise exceptions } catch { // handle exception a parameter of a built-in or custom exception class to get an error detail. You could use the exception type name as the error code, but each class can have different messages. Maybe you could use the exception object's GetHashCode method and use the hash. I'm not sure that will be unique for each message type though.

Another method would be to get the error code from the exception class directly. For example:

catch (Exception ex)
{
    if (ex.InnerException is ServiceResponseException)
       {
        ServiceResponseException srex = ex.InnerException as ServiceResponseException;
        string ErrorCode = srex.ErrorCode.ToString();
       }
}

How catch exception codes / error code in C#, C# exception handling is built upon four keywords: try, catch, finally, and throw. handling code } catch( ExceptionName eN ) { // error handling code } finally  Examples. The following code example throws and then catches an Exception exception and displays the exception's text message using the Message property. // Example for the Exception::HelpLink, Exception::Source, // Exception::StackTrace, and Exception::TargetSite properties. using namespace System; namespace NDP_UE_CPP { // Derive an exception; the constructor sets the HelpLink and // Source

Exception Handling in C#, You know you have code similar to this: try { File.WriteAllText(path, contents); } catch (Exception e) { logger.Error(e); }. Simply catching  Run the code, put a break point in your catch block, and use the debugger to look at the exception and see what information you have. – Joel Coehoorn Aug 1 '11 at 0:03 Alternatively, you could run the code without bothering to debug and print out the Exception type with GetType (). But Joel's answer will also do the trick for sure.

C# - Exception Handling, It's that simple. In certain scenarios where, let's say, a C programmer would return an error code, a Java or C#  System Exception is predefined Exception class in C# that is ready to use in programming. Just choose which exception may occur in your code and use it in a catch block. It this chapter we are listing complete list of system exception class. You can use this exception for writing error free and robust code.

C# exception handling best practices, C# Exception handling uses the try, catch, and finally keywords to attempt actions that may not succeed, to handle failures, and to clean up resources afterwards. try { //your code here } Catch (exception type) { //your code here }

Comments
  • Run the code, put a break point in your catch block, and use the debugger to look at the exception and see what information you have.
  • Alternatively, you could run the code without bothering to debug and print out the Exception type with GetType(). But Joel's answer will also do the trick for sure.
  • You should only catch the exact type of exception you expect; catching Exception is almost always a bad code smell.
  • @Bevan catching Exception is almost always good idea. Because you don't have to show a message at once — an every class shouldn't know does the app works with GUI or terminal. So you just have to save an exception ID to show it in a far far away. No need to catch every exception exclusively to do the same thing. At least it was the way I worked in C++. Now I'm work with C#, but don't see a reason that could make here a difference.
  • Since this question is kinda old, this is just a reminder for people who would like to use this answer: For .NET 3.0, 3.5 and 4.0 you will have to use reflection to get the value of the HResult property as it is marked protected. Source: stackoverflow.com/questions/15462675/…
  • Small improvement in C# 6, you can change your first if statement to the bottom line. The first part checks for null, and fails the if condition when winEx == null. Then it safely checks the ErrorCode property without throwing a null exception. if (winEx?.ErrorCode == ErrorCode)