Reed
Reed

Reputation: 1642

Defining and catching new custom exception of custom type

I have the following exception that I created for my testing scenarios:

    class EvaluationException : Exception
    {
        public PrettyError ExceptionDetails { get; }
        public EvaluationException(PrettyError exceptionDetails)
        {
            this.ExceptionDetails = exceptionDetails;
        }
    }

And I'd like to use the following catch block

catch (Exception e)
{
    if(e is EvaluationException)
    {
        e.ExceptionDetails //do stuff;
    }
}

However e.ExceptionDetails does not contain a definition for ExceptionDetails. I've tried casting a la (EvaluationException)e and e = e as EvaluationException and I still cannot access the new class attribute that I declared for my custom exception.

How can I do this?

Upvotes: 0

Views: 106

Answers (2)

David
David

Reputation: 218827

Specific Problem

e is still the wrong type. When you do this:

if(e is EvaluationException)
{
    e.ExceptionDetails //do stuff;
}

You're not actually modifying the type of e. It's still an Exception, which indeed doesn't have that property. In order to access that property, you need to interpret e as that type when reading it:

if(e is EvaluationException)
{
    (e as EvaluationException).ExceptionDetails //do stuff;
}

or perhaps:

if(e is EvaluationException)
{
    var ex = e as EvaluationException;
    ex.ExceptionDetails //do stuff;
}

Taking a Step Back

Though, since this is in a catch block, you may make better use of the tooling (and end up with better organized code) to separate your exception handlers by type:

try
{
    //...
}
catch (EvaluationException e)
{
    // specific handling for this exception type
}
catch (Exception e)
{
    // catch-all for non-specific exceptions
}

You can chain as many of those as you like. This allows the runtime to determine which catch block to use, so your code can focus on handling the exception instead of cluttering itself up with trying to determine the exception.

Upvotes: 4

stephanV
stephanV

Reputation: 183

The casting does not work because e is already of type Exception. If you assign to a new variable it would work.

You can also catch specific exception types to make yor life easier like:

catch (EvaluationException evalex)
{
    //do stuff
}
catch (Exception ex)
{
  // do other stuff
}

Upvotes: 4

Related Questions