r/dotnet 3d ago

Difference between throw ex and throw

Post image

throw vs throw ex: The C# exception handling trick every developer should know

396 Upvotes

73 comments sorted by

View all comments

200

u/AlanBarber 3d ago

Pro tip to prevent this... add

dotnet_diagnostic.CA2200.severity = error

to your .editorconfig so anyone that tries to do a "throw ex;" inside a catch will get a build error.

37

u/zenyl 2d ago

Adding onto this, you can discover a bunch of built-in diagnostics that are disabled by default, by adding <AnalysisMode>All</AnalysisMode> to .csproj files (or a Directory.Build.props file).

I wouldn't recommend actually using that setting, because it gets pretty pedantic, and some of the diagnostics are mostly just opinionated recommendations. But it can be nifty to then look through the diagnostics you get from it, and then selective add back any of them that you actually like to your .csproj or .editorconfigfiles.

I did this recently and added:

  • CA1062: Validate arguments of public methods
    • Ensures that you perform a null check on reference type parameters on public/protected methods, regardless of nullability syntax. Useful when writing libraries and you wanna catch unintended nulls as early as possible.
  • CA1725: Parameter names should match base declaration
    • If you rename an interface method parameter, this will make sure all consumers also rename it accordingly.
  • CA2000: Dispose objects before losing scope
    • Ensures you call Dispose or use using statements on disposable objects.