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
isto keep each test tightly scoped:(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.