Created
April 11, 2012 19:20
-
-
Save danlash/2361616 to your computer and use it in GitHub Desktop.
.NET Exceptions Thrown By Event Handlers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> EventExceptions.exe | |
Before Exception | |
Implicit caught: Exception! | |
Before Exception | |
Explicit caught: Exception! | |
After Exception | |
> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if you explicitly invoke your event handlers, you can 'continue' your event publication