Search code examples
c#.netexpression-trees

Represent try..catch without exception variable or filter using expression tree factory methods


Which factory method in System.Linq.Expressions.Expression should I call to create an expression tree -- more specifically, a CatchBlock instance -- which represents the catch in the following C# code:

try {
    // ...
} catch {
    // ...
}

All the overloads of the Catch method seem to require either an exception type -- the equivalent of this:

catch (Exception) {
    // ...
}

and/or a ParameterExpression which will be bound to the exception -- the equivalent of this:

catch (Exception ex) {
    // ...
}

Passing null into the first argument (and casting to Type to avoid ambiguity):

// using static System.Linq.Expressions.Expression

Catch((Type)null, Constant(true));

causes an ArgumentNullException.

The MakeCatchBlock method has the same behavior


Solution

  • The usage of try {...} catch {...} to catch exceptions thrown from non .Net components and therefor don't inherit from System.Exception is misguided since the CLR automatically wraps such exceptions with a RuntimeWrappedException which obviously does inherit System.Exception - and therefor you can use try {...} catch(Exception e) {...} to catch thous exceptions as well.

    Therefor, there is no need to handle the plain try {...} catch {...} separately from try {...} catch (Exception e) {...} since they both will catch all exceptions.