Tom
Tom

Reputation: 1057

Create a custom exception using C#

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?

Upvotes: 2

Views: 9396

Answers (2)

Humn
Humn

Reputation: 36

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);
        }

Upvotes: 2

shahkalpesh
shahkalpesh

Reputation: 33484

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

EDIT:

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

Upvotes: 0

Related Questions