How to get Exception Error Code in C# - c#

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.

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.

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.

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
}

catch (Exception e)
{
if (e is MyCustomExeption myEx)
{
var errorCode = myEx.ErrorCode;
}
}

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();
}
}

Related

Trying to get exception code from .NET 3.5 without success

I have a web service. Within a method, I have a try-catch block. Then within it, I would like to get the exception code.
I have tried below:
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
}
... that is explained here but in my case, it is not working: When casting exception e as Win32Exception I get a null and also once I get a null and I try to cast e.InnerException as Win32Exception I get null as well.
Below a screenshot with my exception:
As you can see there is a HResult code.
According to your screenshot, you're catching an instance of SoapException: https://learn.microsoft.com/en-us/dotnet/api/system.web.services.protocols.soapexception?view=netframework-3.5
This class doesn't inherit from Win32Exception, that's why the type cast operator returns null. You should be able to get HResult field right from the base Exception class (even in .Net 3.5, according to the docs):
catch (Win32Exception w32ex)
{
// Put your current code here...
}
catch (Exception ex)
{
int hResult = ex.HResult;
// Handle HRESULT error code here...
}

C# - Exception handling from within finally clause

The title is a bit misleading but the issue seems very straight-forward to me. I have try-catch-finally block. I want to execute the code in the finally block only if an exception was thrown from the try block. The structure of the code right now is:
try
{
//Do some stuff
}
catch (Exception ex)
{
//Handle the exception
}
finally
{
//execute the code only if exception was thrown.
}
Right now the only solution I can think of is setting a flag like:
try
{
bool IsExceptionThrown = false;
//Do some stuff
}
catch (Exception ex)
{
IsExceptionThrown = true;
//Handle the exception
}
finally
{
if (IsExceptionThrown == true)
{
//execute the code only if exception was thrown.
}
}
Not that I see something bad in this but wonder if there is another(better) approach to check if there's a thrown exception?
What about something like:
try
{
// Do some stuff
}
catch (Exception ex)
{
// Handle the exception
// Execute the code only if exception was thrown.
}
finally
{
// This code will always be executed
}
That's what Catch block are made for!
Don't use finally for this. It is intended for code that should always execute.
What exactly is the difference, in terms of when to execute, between
//Handle the exception
and
//execute the code only if exception was thrown.
I can't see any.
You don't need finally after all:
try
{
//Do some stuff
}
catch (Exception ex)
{
//Handle the exception
//execute the code only if exception was thrown.
}
The Finally part of a Try / Catch statement is always fired regardless of whether any exceptions have been found. I would recommend you don't use it in this scenario.
try
{
// Perform Task
}
catch (Exception x)
{
//Handle the exception error.
}
Finally
{
// Will Always Execute.
}

Catch InvalidOperationException with empty structure

I am trying to catch the InvalidOperationException that can sometimes occur when declaring variables. The following code doesn't work however. Probably because I don't really know how you catch an exception.
public override void Download()
{
try
{
var t = (ForumThread)Globals.Db.Thread.Get(_extIdForumThread, _idF);
try
{
throw new InvalidOperationException();
}
catch (InvalidOperationException exception)
{
return;
}
catch (Exception exception)
{
throw;
}
}
}
Any help at all would be very appreciated.
You don't need to throw the exception yourself. Just have:
try
{
var t = (ForumThread)Globals.Db.Thread.Get(_extIdForumThread, _idF);
}
catch (InvalidOperationException exception)
{
// Error logging, post processing etc.
return;
}
You shouldn't really be catching the general exception either unless you have a really good reason to - i.e. your application cannot crash, but if you do you need to be able to recover from it.

C# Catch re-throw/propagation for a specific exception type

I am trying to propagate to my UI the GatewayConnectionFailedException as you can see. I want this code to catch everything except that exception which I want the presentation layer to catch to notify the user that the database was the problem so he can go and fix it. My problem is that when I throw it the first time then I get GatewayConnectionFailedException not handled by user code on the GatewayException catch clause.
Its also important to note the the GatewayConnectionFailedException extends GatewayException which extends Exception. Is there something I am missing or will I have to move all the catch to the presentation layer ?
try
{
something();
}
catch (GatewayConnectionFailedException gcfe)
{
throw;
}
catch (GatewayException ge)
{
if (ge.GetType() == typeof(GatewayConnectionFailedException))
throw;
string errMsg = "Records could not be retrieved due to a data gateway error. " + GetTypeInfo();
_logger.Error(errMsg + "\r\n{0}", ge);
}
catch (Exception e)
{
if (e.GetType() == typeof(GatewayConnectionFailedException))
throw;
string errMsg = "Records could not be retrieved due to an unexpected error. " + GetTypeInfo();
_logger.Error(errMsg + "\r\n{0}", e);
}
Stupid question... is your UI code try-catching in it's call to this layer? Something has to handle that second throw...
In a nutshell, it sounds like you're trying to do this:
using System;
namespace ConsoleApplication1
{
class ExceptionA : Exception
{
public override string Message
{
get
{
return "Exception A";
}
}
}
class ExceptionB : ExceptionA
{
public override string Message
{
get
{
return "Exception B";
}
}
}
class Program
{
static void Main(string[] args)
{
try
{
DoThing();
}
catch (Exception ex)
{
Console.WriteLine("Caught in 'UI' code: " + ex.Message);
}
}
static void DoThing()
{
try
{
throw new ExceptionB();
}
catch (ExceptionB ex)
{
Console.WriteLine("Caught B");
throw;
}
catch (ExceptionA ex)
{
Console.WriteLine("Caught A");
}
catch (Exception ex)
{
Console.WriteLine("Caught Generic");
}
}
}
}
Which yields this output:
Caught B
Caught in 'UI' code:
Exception B
Press any key to continue...
It just seems like you don't have anything catching the 2nd thrown exception, which is why it's "unhandled." If we comment out the try-catch in main, we end up with an unhandled exception:
static void Main(string[] args)
{
//try
//{
DoThing();
//}
//catch (Exception ex)
//{
//Console.WriteLine("Caught in 'UI' code: " + ex.Message);
//}
}
Yielding the following output:
Caught B
Unhandled Exception: ConsoleApplication1.ExceptionB: Exception B
at ConsoleApplication1.Program.DoThing() in C:\Users\Giovanni\AppData\Local\T
emporary Projects\ConsoleApplication1\Program.cs:line 50
at ConsoleApplication1.Program.Main(String[] args) in C:\Users\Giovanni\AppDa
ta\Local\Temporary Projects\ConsoleApplication1\Program.cs:line 33
Press any key to continue . . .
One item to not although this might not fix the exception, if you are catching and rethrowing the exception use this code instead:
catch (GatewayConnectionFailedException)
{
throw;
}
this way the stacktrace reflects the programs journey more accurately. It may not solve the issue though.
Hard to tell what is missing without full picture, but one important thing that you should throw exceptions in different way. The syntax should be
throw;
you will have full stacktrace. More info.
Catching of GatewayConnectionFailedException should solve your problem and in catch block just do throw, don't throw the exception object. Answer by Andy is correct.
Secondly I'm assuming GatewayConnectionFailedException inherits from GatewayException.
Select catch sequence in ascending of order of inheritance, child class should come first and then base class.
catch(Child){}
catch(Base){}
catch(Exception) {} //Base class for all exceptions
to start your try catch is redundant. the first catch will handle GatewayConnectionFailedException the remaining catches will never be of type GatewayConnectionFailedException because they were handled by the first catch. so the code can be simplified to
try
{
something();
}
catch (GatewayConnectionFailedException)
{
throw;
}
catch (GatewayException e)
{
_logger.Error(e.Message, e);
}
Now how the UI will handle this depends on how you handle the exception. if you just throw the exception, then you need a try catch in the presentation layer as well. However if the return type of this layer returned an object like
class Result<T>
{
T Value {get;set;}
Exception Error {get;set;}
}
Then you could simply process the type without need try/catch in the presentation layer.
Also worth noting is what you are catching and why you are trying to catch it. typically you don't want to catch Exception except at the application layer where you log the error and fail. Exceptions should be exceptional, and therefore only catch exceptions you expect can happen and why they may happen. otherwise let them bubble up.
Instead of using throw exceptionName try only throw.
Edit 1:
Try catching all exceptions in the same block, then throw back the exception only if it's the GatewayConnectionFailedException
try
{
something();
}
catch (Exception e)
{
if (e.GetType() == typeof(GatewayConnectionFailedException))
throw;
string errMsg = "Records could not be retrieved due to an unexpected error. " + GetTypeInfo();
_logger.Error(errMsg + "\r\n{0}", e);
}

Can you catch more than one type of exception with each block? [duplicate]

This question already has answers here:
Catch multiple exceptions at once?
(29 answers)
Closed 9 years ago.
This question is close to what I want to do, but not quite there.
Is there a way to simplify the following code?
private bool ValidDirectory(string directory)
{
if (!Directory.Exists(directory))
{
if (MessageBox.Show(directory + " does not exist. Do you wish to create it?", this.Text)
== DialogResult.OK)
{
try
{
Directory.CreateDirectory(directory);
return true;
}
catch (IOException ex)
{
lblBpsError.Text = ex.Message;
}
catch (UnauthorizedAccessException ex)
{
lblBpsError.Text = ex.Message;
}
catch (PathTooLongException ex)
{
lblBpsError.Text = ex.Message;
}
catch (DirectoryNotFoundException ex)
{
lblBpsError.Text = ex.Message;
}
catch (NotSupportedException ex)
{
lblBpsError.Text = ex.Message;
}
}
}
return false;
}
It seems a waste, and if I later want to change how I report an error back to the user, or perhaps I want to log these errors, or whatever, then I've got to change 5 different catch blocks. Am I missing something, or is this blatantly against code-reuse?
Am I just trying to be (too) lazy?
You can use :
catch (SystemException ex)
{
if( (ex is IOException)
|| (ex is UnauthorizedAccessException )
// These are redundant
// || (ex is PathTooLongException )
// || (ex is DirectoryNotFoundException )
|| (ex is NotSupportedException )
)
lblBpsError.Text = ex.Message;
else
throw;
}
If the exceptions share a common super-class then you can just catch the superclass.
Yes, you're trying to be lazy, but laziness is one of the virtues of a programmer, so that's good.
As for your question: There is no way I am aware of, but there are some workarounds available:
Give the Exceptions a common ancestor. I think this won't be possible in your case, since they seem to be builtin.
Catch the most generic exception you can.
Move the handling code into its own function and call that from each catch block.
This is annoying, and other answers have suggested good workarounds (I'd use #Lotfi's).
However this behaviour is a requirement given the type-safety of C#.
Suppose you could do this:
try
{
Directory.CreateDirectory(directory);
return true;
}
catch (IOException,
UnauthorizedAccessException,
PathTooLongException,
DirectoryNotFoundException,
NotSupportedException ex)
{
lblBpsError.Text = ex.Message;
}
Now what type is ex? They all have .Message because they inherit System.Exception, but try accessing any of their other properties and you have a problem.
Its also important to note that when catching more then one type of exception they should be order by most specify to most general. The Exception will find the first one in the list that it matches and throw that error, none of the other errors will be thrown.
Just for completeness’ sake:
In VB, you could use conditional exception handling:
Try
…
Catch ex As Exception When TypeOf ex Is MyException OrElse _
TypeOf ex Is AnotherExecption
…
End Try
Such a Catch block would only get entered for the specified exceptions – unlike in C#.
Perhaps a future version of C# will offer a similar feature (after all, there's a specific IL instruction for that code).
MSDN: How to: Filter Errors in a Catch Block in Visual Basic
Check out the The Exception Handling Application Block from EntLib. They articulate a very nice policy and configuration based exception handling methodology that avoids large conditional logic blocks.
You can catch a base class exception (all your exceptions derive from SystemException):
try
{
Directory.CreateDirectory(directory);
return true;
}
catch (SystemException ex)
{
lblBpsError.Text = ex.Message;
}
But then you may end up catching exceptions you don't want to catch.
You can do
ex.GetType()
see http://msdn.microsoft.com/en-us/library/system.exception.gettype.aspx
EDIT
try
{
Directory.CreateDirectory(directory);
return true;
}
catch (Exception ex)
{ switch(ex.GetType())
case .....
case ..........
blBpsError.Text = ex.Message;
}
I understand some of these exceptions may not be foreseeable but where possible try to implement your own "pre-emptive" logic. Exceptions are expensive, though in this case probably not a deal breaker.
For example, use Directory.GetAccessControl(...) rather than relying on an UnauthorizedAccessException to be thrown.
You could use delegates, this will do what you want:
EDIT: simplified a bit
static void Main(string[] args)
{
TryCatch(() => { throw new NullReferenceException(); },
new [] { typeof(AbandonedMutexException), typeof(ArgumentException), typeof(NullReferenceException) },
ex => Console.WriteLine(ex.Message));
}
public static void TryCatch(Action action, Type[] exceptions, Action<Exception> catchBlock)
{
try
{
action();
}
catch (Exception ex)
{
if(exceptions.Any(p => ex.GetType() == p))
{
catchBlock(ex);
}
else
{
throw;
}
}
}
Your particular try/catch would be:
bool ret;
TryCatch(
() =>
{
Directory.CreateDirectory(directory);
ret = true;
},
new[]
{
typeof (IOException), typeof (UnauthorizedAccessException), typeof (PathTooLongException),
typeof (DirectoryNotFoundException), typeof (NotSupportedException)
},
ex => lblBpsError.Text = ex.Message
);
return ret;

Categories