this post was submitted on 21 Feb 2025
905 points (95.6% liked)

Programmer Humor

20735 readers
406 users here now

Welcome to Programmer Humor!

This is a place where you can post jokes, memes, humor, etc. related to programming!

For sharing awful code theres also Programming Horror.

Rules

founded 2 years ago
MODERATORS
 
you are viewing a single comment's thread
view the rest of the comments
[–] codexarcanum@lemmy.dbzer0.com 12 points 1 day ago (1 children)

This is incorrect. The C# is valid. Throw in a catch statement simply rethrows the caught exception. Source: I've been writing C# for 20 years, also the docs.

I won't act like MS absolutely didn't steal core concepts and syntax from Java, but I've always thought C# was much more thoughtfully designed. Anders Hejlsberg is a good language designer, TypeScript is also a really excellent language.

[–] jaybone@lemmy.world 3 points 1 day ago (1 children)

In Java you would say “throw e;” (to rethrow the same exception you just caught.)

You wouldn’t just say “throw”

Or you could also throw some other exception. But the syntax requires you specify what it is you are throwing. (And sane in C++, where you could throw any object, even a primitive.)

So that was my question.

[–] codexarcanum@lemmy.dbzer0.com 6 points 1 day ago (1 children)

Wildly, in C# you can do either and it has different results. I believe a bare throw doesn't append to the stack trace, it keeps the original trace intact, while throw e updates the stack trace (stored on the exception object) with the catch and rethrow.

In C#, you can only throw objects whose class derives from Exception.

[–] Hoimo@ani.social 1 points 1 day ago

You can do either, but you usually do neither. The best way is to throw a new exception for your situation and add the caught exception as an inner exception. Because rethrowing resets the stack trace, removing the context from an exception message that is often pretty vague, and "bouncing" with throw; doesn't tell the next exception handler that you already handled (part of) the exception.