2

I am trying to override the System.Exception class with my own exception class. I would like to add the parameter "code".

I would want to do this:

throw new MyException(code, "message");

Then catch the exception using something like this:

catch (MyException e) {
    Console.WriteLine(e.code)
}

Update: The problem was that I needed to catch the exception as "(MyException e)" instead of "(Exception e)"

This is my code so far:

public class MyException : System.Exception
{
    public String ErrorCode = "";

    public MyException() : base()
    {
    }

    public MyException(string message, string code) : base(message)
    {
        this.ErrorCode = code;
    }
    public MyException(string message, Exception inner, string code) : base(message, inner)
    {
        this.ErrorCode = code;
    }
}

This gives me an error that "System.Exception does not contain a definition for 'ErrorCode'...". What am I doing wrong?

4
  • 4
    My guess is that you accidentally have catch (Exception e) instead of catch (MyException e) Commented Mar 13, 2012 at 11:52
  • Indeed Rob, the class compiles just fine on it's own. Commented Mar 13, 2012 at 11:54
  • OT: You're swapping the arguments in the call. Commented Mar 13, 2012 at 11:54
  • Tom: pinpoint the line and make sure you post the exact code that produces the error. Commented Mar 13, 2012 at 11:55

2 Answers 2

2

I have test your code,the exception class is right,but the catch is wrong.My test code is this.

        catch (MyException ex)
        {
            Console.WriteLine(ex.ErrorCode);
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, indeed I was trying to catch the error as a "exception" instead of "MyException"
0

That is because it is ErrorCode and not Code.
Also, make that a public readonly property.

EDIT:

catch (MyException e) {
    Console.WriteLine(e.ErrorCode)
}

5 Comments

The error message states that it's ErrorCode that's missing.
@svick: Please take a look at the accepted answer. When downvoting, please help me understand the reason. Thanks.
I think your answer doesn't actually answer the question, because that's not what the problem was. Of course, correctly answering questions like this requires a crystal ball, which is why I did not downvote your answer.
@svick: Thanks for not downvoting. What do you think the problem was other than wrong code pasted by OP? If the question is wrong, it should be deleted. Isn't it?
The problem was catching Exception instead of MyException, the OP says that in the update to the question. I think you're right that this question should be deleted, which is why I already voted to close it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.