💡 𝐂#/.𝐍𝐄𝐓 𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝐇𝐚𝐧𝐝𝐥𝐢𝐧𝐠 𝐓𝐢𝐩 🔥 💎𝐃𝐨𝐧'𝐭 𝐮𝐬𝐞 𝐭𝐡𝐫𝐨𝐰 𝐞𝐱 𝐢𝐧 𝐜𝐚𝐭𝐜𝐡 𝐛𝐥𝐨𝐠 🚫 𝐭𝐡𝐫𝐨𝐰 𝐞𝐱; updates the StackTrace property of ex. If you throw the "ex", 𝐭𝐡𝐞 𝐬𝐭𝐚𝐜𝐤 𝐭𝐫𝐚𝐜𝐞 𝐢𝐬 𝐥𝐨𝐬𝐭! ✅ 𝐭𝐡𝐫𝐨𝐰; preserves the original stack trace of exception stored in the 𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧.𝐒𝐭𝐚𝐜𝐤𝐓𝐫𝐚𝐜𝐞 property. ⚡ In this way, 𝐰𝐞 𝐝𝐨𝐧𝐭 𝐥𝐨𝐬𝐞 𝐭𝐡𝐞 𝐬𝐭𝐚𝐜𝐤 𝐭𝐫𝐚𝐜𝐞 and can quickly find the root cause of the error. ⚠️ 𝐂𝐀𝟐𝟐𝟎𝟎 𝐖𝐚𝐫𝐧𝐢𝐧𝐠 • CA2200 is a code analysis rule that detects improper exception re-throwing. • It triggers when you use throw ex; instead of throw; in catch blocks. • Following this rule helps maintain complete error information for troubleshooting. ⚠️ 𝐭𝐡𝐫𝐨𝐰 𝐞𝐱, 𝐰𝐢𝐥𝐥 𝐫𝐞𝐬𝐞𝐭 𝐭𝐡𝐞 𝐜𝐚𝐥𝐥 𝐬𝐭𝐚𝐜𝐤 𝐢𝐧 𝐭𝐡𝐞 𝐞𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝐭𝐨 𝐭𝐡𝐞 𝐩𝐨𝐢𝐧𝐭 𝐰𝐡𝐞𝐫𝐞 𝐭𝐡𝐢𝐬 𝐭𝐡𝐫𝐨𝐰 𝐬𝐭𝐚𝐭𝐞𝐦𝐞𝐧𝐭 𝐥𝐨𝐬𝐞𝐬 𝐭𝐡𝐞 𝐢𝐧𝐟𝐨𝐫𝐦𝐚𝐭𝐢𝐨𝐧 𝐚𝐛𝐨𝐮𝐭 𝐰𝐡𝐞𝐫𝐞 𝐭𝐡𝐞 𝐞𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝐰𝐚𝐬 𝐜𝐫𝐞𝐚𝐭𝐞𝐝. So, we can't see the original stack trace and you may spend days to find the root cause. #csharp #dotnet #programming #softwareengineering #softwaredevelopment
One small keyword, massive debugging difference. throw; keeps the truth, throw ex; rewrites history.
SERKUT YILDIRIM Such an easy mistake to make. throw ex; looks harmless… until you’re debugging and the stack trace is gone. One of those small details that makes a huge difference later.
A leader is best when people barely know he exists... when his work is done, his aim fulfilled, they will say: we did it ourselves.
This is one of those small details with huge impact during production incidents. Stack trace integrity is everything when diagnosing issues under pressure.
his is arguably the most important 'day one' lesson for any .NET developer. Nothing is more frustrating than chasing a production bug only to find a 'teleported' stack trace that hides the true source of the error.
Thanks for sharing
Thanks for sharing
Note: you can rethrow an exception if you enrich it with more details, or use it as InnerException in the new one
Great tip. Preserving the original stack trace with throw; makes debugging much easier, throw ex; can hide the real issue.
RULE: IF you LOG ex, then THROW ex! Pick one: - LOG ex - THROW (without ex) Never both. DRY!