views:

1012

answers:

3

In VB.NET I often Catch ... When ...

Try
  ' Some code'
Catch e As ArgumentNullException When e.ParamName.ToUpper() = "SAMPLES"
  ' Handle the error'
End Try

Is there a C# equivalent to Catch ... When?

I don't want to resort to using an if statement inside a catch if possible.

+13  A: 

i think there's none. you'll really have to resort to an if statement inside your catch then rethrow if your condition isn't fulfilled

cruizer
+8  A: 

That won't recreate the same semantics as the VB Catch When expression. There is one key difference. The VB When expression is executed before the stack unwind occurs. If you were to examine the stack at the point of a when Filter, you would actually see the frame where the exception was thrown.

Having an if in the catch block is different because the catch block executes after the stack is unwound. This is especially important when it comes to error reporting. In the VB scenario you have the capability of crashing with a stack trace including the failure. It's not possible to get that behavior in C#.

EDIT:

Wrote a detailed blog post on the subject.

JaredPar
are you sure? you can just use 'throw;' instead of 'throw e;'
Nicholas Mancuso
100% It has nothing to do with throw. It's when the expression called by When is executed. In VB it will happen while the exception raise point is still on the stack.
JaredPar
In c# , Even if the stack is offloaded - the Exception object 'e' still has the stack trace available. but its probably not that helpful as having the entire stack available at debug time. but for runtime loggin info stack trace would suffice?
dotnetcoder
Besides debugging, which can be done more easily in C# by ticking the 'break when an exception is thrown' checkbox, this also matters to whether or not 'finally' clauses are run.
configurator
A: 

I'm with cruizer and Nicholas Mancuso, simply using 'throw' preserves the Stack The Mistake Every C# Programmer Makes

bob31334