How to distinguish different types of exceptions in the BackgroundWorker.RunWorkerCompleted event handler

I am doing a small hobby project in C #, a language that I don’t know well, and stumbled upon the following:

Suppose you are using the asynchronous operation used by BackgroundWorker. Now, if there is an exception, the RunWorkerCompleted event will be raised, and the RunWorkerCompletedEventArgs.Error will be non-zero.

Is the next canonical path handling different types of exceptions? (Here, all kinds of exceptions are inherited from the WRT siblings)

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 good.

+4
source share
4 answers

You can use is so that each test is limited:

 if (e.Error is FirstKindOfException ) { ... } else if (e.Error is SecondKindOfException) { ... } 

(then reuse if you want to get special values ​​from the exception)

Honestly, it’s quite rare that I need to handle many different types of exceptions. In most cases, it is normal to simply restore (compensate) a known state and report the error accordingly. I usually prefer to check for probable errors before the action starts, so the exception is really something exceptional.

+7
source

Use the is statement:

 if (e.Error is FirstKindOfException) { //... } else if (e.Error is SecondKindOfException) { //... } //etc.. 

Or simply abbreviate it, since you don't know how to handle these exceptions anyway. If you did this, you would catch them in the DoWork () event handler, it makes no sense to try to process them after the state has evaporated:

 if (e.Error != null) throw new BackgroundTaskFailedException(e.Error); 
+5
source

Using is operator can?

 if (e is OneKindOfException) { } else if (e is SecondKindOfException) { } 
+2
source

Yes, you can do this, but it really depends on what you are going to do with all these types of exceptions. Usually this will only be displayed to the user, so there is no need to check the type of error.

You also need to keep in mind that the type of exception may be an AggregateException - which is returned from Task<T> operations, so you need to be careful.

+1
source

All Articles