Problem:
I would like to catch any exceptions from any method in a class so that I may record class specific data to the exception for logging before it is passed up the stack. I know that I can put a try-catch in every method of the class, but there are many methods and It seems there should be a more efficient way.
Example of what I am currently doing:
public class ClassA
{
private int x;
private int y;
public void Method1()
{
try
{
//Some code
}
catch(Exception ex)
{
ex.Data.Add("x", x);
ex.Data.Add("y", y);
throw;
}
}
public void Method2()
{
try
{
//Some code
}
catch (Exception ex)
{
ex.Data.Add("x", x);
ex.Data.Add("y", y);
throw;
}
}
}
Example of what I would like to do:
public class ClassB : IUnhandledErrorHandler
{
private int x;
private int y;
public void Method1()
{
//Some code
}
public void Method2()
{
//Some code
}
void IUnhandledErrorHandler.OnError(Exception ex)
{
ex.Data.Add("x", x);
ex.Data.Add("y", y);
throw;
}
}
public interface IUnhandledErrorHandler
{
void OnError(Exception ex);
}
Note: This class is a service in a WCF project and implements a ServiceContract. I have tried adding an ErrorHandler to the service's ChannelDispatcher. However, when the error reaches the ErrorHandler it is already beyond the scope of the class where the error occurred, so I cannot access the class details.
Solution:
public class ClassC
{
public ClassC()
{
AppDomain.CurrentDomain.FirstChanceException += OnError;
}
private int x;
private int y;
public void Method1()
{
//Some code
}
public void Method2()
{
//Some code
}
private void OnError(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
{
e.Exception.Data["x"] = x;
e.Exception.Data["y"] = y;
}
}
In C#, You can use more than one catch block with the try block. Generally, multiple catch block is used to handle different types of exceptions means each catch block is used to handle different type of exception.
An unhandled exception is an exception that does not have an associated handler. In C++ any unhandled exception terminates the program. It is unspecified whether the stack is unwound in this case, i.e. destructors of successfully constructed local variables may be executed or not depending on the compiler.
ASP.NET Core Error Handling You can register it as a global filter, and it will function as a global exception handler. Another option is to use a custom middleware designed to do nothing but catch unhandled exceptions. You must also register your filter as part of the Startup code.
Master C and Embedded C Programming- Learn as you go Exception handling is used to handle the exceptions. We can use try catch block to protect the code. Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.
If you run on .NET 4, you might use the FirstChanceException event from the AppDomain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With