Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell apart different exception types in BackgroundWorker.RunWorkerCompleted event handler

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.

like image 442
Laurynas Biveinis Avatar asked Dec 07 '22 01:12

Laurynas Biveinis


2 Answers

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.

like image 125
Marc Gravell Avatar answered Dec 09 '22 15:12

Marc Gravell


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);
like image 39
Hans Passant Avatar answered Dec 09 '22 13:12

Hans Passant