Handling Exceptions of Different Types

2
try {
    await DoFooAsync();
} catch (Exception e) {
    if(e is TaskCancelledException || e is UnauthorizedAccessException) {
        // ...
    }
    throw;
}

The block catch of the above excerpt checks the type of exception captured with a conditional block. As I will do the same treatment for TaskCancelledException and UnauthorizedAcessException , to avoid rewriting code with two catch blocks with the same calls, I did as above.

However, there is another way to do it using statement when . See:

try {
    await DoFooAsync();
} catch (Exception e) when (e is TaskCancelledException || e is UnauthorizedAccessException) {
    // ...
}

There is no practical difference. As far as I can tell, the two are the same.

What's the difference in running both? Which is better and why?

    
asked by anonymous 22.09.2017 / 05:51

1 answer

6

There is, the first one changes the stack trace , the second does not.

The first one intercepts the thrown exception and throws another exception there at that location. The content may even be the same, but the location is different. The second keeps the stack trace intact indicating the actual source of the error, so this is preferable. As the exception bubbling to other places will see that it shows the origin in a different place, the first one will consider that the exception occurred there, but it occurred before.

It is not a feature that will be very necessary, at least if the person his exception in a correct way, ie, does not capture anything, but is useful when needed. It was put in the language because the C # compiler needed this to work properly.

One guy replied to the SO about this: P

    
22.09.2017 / 06:02