I am doing little hobby project in C#, a language I do not know well, and have stumbled upon the following:
Suppose you have an asynchronous operation implemented by using BackgroundWorker. Now if there is an exception, event RunWorkerCompleted will be raised and RunWorkerCompletedEventArgs.Error will be non-null.
Is the following the canonical way then to handle different exception types? (Here all the exception kinds are siblings WRT inheritance)
if (e.Error != null)
{
FirstKindOfException e1 = e as OneKindOfException;
SecondKindOfException e2 = e as SecondKindOfException;
...
LastKindOfException en = e as LastKindOfException;
if (e1 != null)
{
...
}
else if (e2 != null)
{
...
}
...
else
{
...
}
}
It works, but... it doesn't feel right.
You could use is
to keep each test tightly scoped:
if (e.Error is FirstKindOfException )
{
...
}
else if (e.Error is SecondKindOfException)
{
...
}
(then re-cast if you want special values from the exception)
To be honest, though, it is pretty rare that I need to handle lots of different types of exceptions. In most cases, it is fine to simply recover (compensate) to a known state and report the error appropriately. Generally I prefer to test for likely errors before I start the action, so an exception truly is something exceptional.
Use the is operator:
if (e.Error is FirstKindOfException) {
//...
}
else if (e.Error is SecondKindOfException) {
//...
}
//etc..
Or just cut it short since you don't know how to handle these exceptions anyway. If you did then you would have caught them in the DoWork() event handler, there's no point in trying to handle them after the state has evaporated:
if (e.Error != null) throw new BackgroundTaskFailedException(e.Error);
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