this post was submitted on 17 Jun 2023
144 points (96.8% liked)

Programmer Humor

32174 readers
994 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS
 

Brilliant exception handling I found in an app i had to work on

you are viewing a single comment's thread
view the rest of the comments
[–] bartimeo 1 points 1 year ago (2 children)

I am a somewhat new C# developer (2 years). Could you explain more about this?

[–] CatPoop 1 points 1 year ago* (last edited 1 year ago)

An exception will bubble up the stack until it enters a catch block that can handle it, and you may need additional logic to decide if you are finished, or it needs to go further up. (you may also intercept it just to add more data, or log it)

throw; allows you send the original exception further up, but throw ex; behaves the same as throwing a new Exception object, and therefore has a new trace. The throw statement doesn’t query any properties on the exception argument AFAIK, so it has no idea this exception has been previously thrown, but the IDE is smart enough to know you almost certainly don’t want to do this.

[–] [email protected] 1 points 1 year ago

throw ex; treats ex as a new exception, so, it starts a new stack trace for it from itself and deletes stack trace that was saved in ex.StackTrace. On the other hand, throw; takes already present exception in the scope and throws it without modifying the stack trace, preserving the original method that threw ex in the stack trace.

I feel like I wrote the same thing twice. I'm a bit bad with explaining stuff, feel free to ask more specific questions if you still don't understand the difference.