Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any event which gets triggered whenever there is an exception?

Tags:

c#

.net

Is there any event in .Net framework which gets fired on exception. Whenever there is an exception is caught, i need to log it. So if there an event exist, i can subscribe to that and can log the exceptio in the event handler.

like image 845
Kapil Avatar asked Aug 09 '10 14:08

Kapil


People also ask

What happens when an exception occurs?

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system.

What happens when you don't handle an exception?

if you don't handle exceptions When an exception occurred, if you don't handle it, the program terminates abruptly and the code past the line that caused the exception will not get executed.

What happens when an exception is thrown C#?

In C#, the catch keyword is used to define an exception handler. If no exception handler for a given exception is present, the program stops executing with an error message.

What does it mean to throw an exception?

In Java terminology, creating an exception object and handing it to the runtime system is called throwing an exception. After a method throws an exception, the runtime system leaps into action to try and find someone to handle the exception.


2 Answers

Yes - there is the UnhandledException event on the AppDomain object:

AppDomain.CurrentDomain.UnhandledException += YourHandler

FYI: You should only use these handlers as a last resort - it is far better to catch exceptions in a try catch block, although this may not always be possible (for example in the case when 3rd party code starts new threads)

Also, this event will only be fired when an exception is unhandled - to my knowledge there is no way of being notified of caught events in this way without attaching a debugger to the process.

like image 77
Justin Avatar answered Nov 15 '22 11:11

Justin


You should have a look at doing some Aspect Oriented Programming with PostSharp, you can write a simple Log attribute and apply it to your whole assembly.

All you need is something like this:

[Serializable]
public class LogAttribute : OnMethodInvocationAspect
{
   public override void OnInvocation(MethodInvocationEventArgs eventArgs)
   {
      try
      {
         eventArgs.Proceed();
      }
      catch(Exception ex)
      {
         // log exception here
      }
   }
}

and apply it to your assembly:

[assembly: Log]
public class ...

It's not everyone's cup of tea, but I've found it a very clean, neat way to avoid doing a lot of boilerplate code in my classes and frees me up to work on functionalities more related to the project itself.

Update: as Kugel pointed out in the comment, this will help you track and log any exceptions thrown during the execution of the method, but if you want to log the state internal to the method you'll need to do a little more work than this.

For instance, you might still need try/catch blocks inside your method which you could use to capture exceptions that are of interest to your class and maybe even wrap them in a custom exception object so you can start adding more useful information like an error code, etc. So long your custom exception has a suitable mechanism of setting its 'Message' property, e.g.

public class DictionaryKeyNotValidException() : Exception
{
   public DictionaryKeyNotValidException(string key)
       : base(GetMessage(key))
   {   
   }

   public ErrorEnum ErrorCode { get { return ErrorEnum.InvalidDictionaryKey; } }

   private string GetMessage(string key)
   {
      return string.Format("ERROR {0} : Invalid dictionary key encountered {1}",
                           ErrorCode.GetHashCode(), key);
   }
}

then in your log attribute, provided you're using Log4Net, you can start logging more useful information:

catch (Exception ex)
{
   // log error
   log.Error(ex);

   // handle exception, rethrow, etc.
   ...
}

Sorry this is becoming a bit long winded..

like image 23
theburningmonk Avatar answered Nov 15 '22 13:11

theburningmonk