Skip to content

Instantly share code, notes, and snippets.

@danlash
Created April 11, 2012 19:20
Show Gist options
  • Save danlash/2361616 to your computer and use it in GitHub Desktop.
Save danlash/2361616 to your computer and use it in GitHub Desktop.
.NET Exceptions Thrown By Event Handlers
> EventExceptions.exe
Before Exception
Implicit caught: Exception!
Before Exception
Explicit caught: Exception!
After Exception
>
using System;
namespace EventExceptions
{
class Program
{
static void Main()
{
var producer = new Producer();
producer.ThrowYourException += (source, args) => Console.WriteLine("Before Exception");
producer.ThrowYourException += (source, args) => { throw new Exception("Exception!"); };
producer.ThrowYourException += (source, args) => Console.WriteLine("After Exception");
producer.Produce();
producer.ProduceExplicitly();
}
}
internal class Producer
{
public event EventHandler<EventArgs> ThrowYourException;
public void Produce()
{
try
{
ThrowYourException(this, new EventArgs());
}
catch (Exception e)
{
Console.WriteLine("Implicit caught: " + e.Message);
}
Console.WriteLine();
}
public void ProduceExplicitly()
{
foreach (EventHandler<EventArgs> handler in ThrowYourException.GetInvocationList())
{
try
{
handler(this, new EventArgs());
}
catch (Exception e)
{
Console.WriteLine("Explicit caught: " + e.Message);
}
}
Console.WriteLine();
}
}
}
@danlash
Copy link
Author

danlash commented Apr 11, 2012

if you explicitly invoke your event handlers, you can 'continue' your event publication

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment