C# – Sending Exceptions as event arguments

cdesign-patternsexceptions

Is it a good idea to send Exceptions as EventArgs in C#? (And not actually throw the Exception).

I have a class that performs a long running asynchronous task. If something goes wrong in the middle of the task, it will raise an Error event. Is it a good idea to add an Exception as part of the event arguments, or would it be better to use enums?

This class is just one of many that implement a certain interface. All classes in this interface raise the Error event when something goes wrong. Each class that implements this interface will run into different types of errors.

What are some of the best practices in a case such as this? Sending an Exception as an argument and not actually throwing it feels a bit wrong.

Best Answer

Is it a good idea to send Exceptions as EventArgs in C#?

Enh? It's not a great idea.

Is it a good idea to add an Exception as part of the event arguments, or would it be better to use enums?

If you have a fixed set of ways the long running task could fail, then the enum may make sense. Since you say that there are a number of implementers for this interface, you likely have an open set of ways it can fail, making the exception more palatable.

What are some of the best practices in a case such as this?

In general, I dislike events for this sort of thing. You're not guaranteed that anyone is listening. Since something has already gone wrong, it's kinda likely that one of your event handlers will go off the rails, interrupting the chain and/or throwing an exception in the handler, leading to problems.

I would look to see if you couldn't change that to more of a single error handler delegate, perhaps using abstract base classes to force it to be provided via constructor rather than added post construction (which you can't really guarantee at compile time).

That said, passing around exceptions is a little smelly, but not terrible in cases like this. I mean, you're catching an exception and asking a strategy to deal with it. Converting the exception to something else (with likely loss of information) seems to be unnecessary overhead/confusion.

Related Topic