Treatment of exceptions of different types

Asked

Viewed 122 times

2

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

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

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

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

There is no practical difference. As far as I could see the two result the same.

What is the difference in the execution of the two? Which is preferable and why?

1 answer

6


There is, yes, the first changes the stack trace, the second no.

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

It is not a resource that will be very necessary, at least if the person your exception correctly, ie does not keep capturing anything, but it is useful when needed. It was put in the language because the compiler of the C# needed this to work properly.

A guy answered in the OS about this :P

  • Great reference :P

  • You can put an example in the codeground (or anywhere else) that proves that the stack trace is changed?

  • @Brunocosta is a question for the Debugger, then there’s no way to demonstrate this other than in VS or something like that. Read this: https://roslyn.codeplex.com/discussions/541301

  • I understood when I read it I thought I was saying that I really changed the value. After all it is a question only of the Bugger.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.