Elnaz
Elnaz

Reputation: 2900

Using exception filtering in c# 6.0 (with typeof()) VS. catching custom exception

I have a method for manage exception handling as below. The Question is that, in case that the typeof exception is our point, which approach is recommended? Using
catch (System.Exception ex) when(ex.GetType() ==typeof(ExcOneException)){...}
or
catch (ExcOneException ex) {...}

public T MyMethod<T>(Func<T> codeToExecute)
    {
        try
        {
            return codeToExecute.Invoke();
        }
        catch (System.Exception ex) when(ex.GetType() ==typeof(ExcOneException) )
        {
            throw new ExcOneException(ex.Message,ex);
        }
        catch (System.Exception ex)
        {
            throw new ExcTwoException(ex.Message, ex);
        }
    }  

UPDATE: My solution has 3 projects, UI, Services and DataAccess. Each part has its own custom Exception-Handler class. Imagine that, the code in question is in service project. All codes should call this method for execution. If there is any run-time error with type of ExcOneException, it means the error is in service section, else, there should be an error in data access part; so, ExcTwoException should be thrown. This approach helps me in bubbling error up to UI level with details. What I didn't know, was that, in the case that we can use C# 6 properties, when I have filtering just on exception type, which approach is better, using catch-when or mentioning exception type as argument of catch?

Upvotes: 7

Views: 2452

Answers (2)

Philipp Elhaus
Philipp Elhaus

Reputation: 124

Simplification & Readability:

You can filter with is, instead of typeof:

catch (Exception ex) when (ex is ExcOneException) { ... }

Chain multiple Exception types:

catch (Exception ex) when (ex is ExcOneException || ex is ExcTwoException) { ... }

Upvotes: 5

Paulo Morgado
Paulo Morgado

Reputation: 14856

Why would you ever consider that? You mention performance. Do you have any measurements that make you suspicious.

Exception filters are there for filtering exceptions that you can't catch by type, which is not your case.

In your code you are, also, not re-throwing the caught exception. You are throwing an new exception with the caught exception as an inner exception which is what you do when you want to wrap the caught exception with a more meaningful one.

If you intention is to re-throw, the correct code is:

    catch (System.Exception ex)
    {
        throw;
    }

Upvotes: 1

Related Questions