开发者

How to create a custom C# exception?

I'm currently learning C#, but I am stuck on something and I can't find a solution for it.

I am trying to create my own Exception class.

The exception is called "InvalidNumberException", it checks if a number is equal to 5. I know it may seem kinda stupid, but I just need to get the idea about creating Custom Exceptions.

So far I found on MSDN that for creat开发者_如何学编程ing the Exception I need these four constructors:

public class InvalidNumberException : System.Exception
{
    public InvalidNumbertException() : base() { }
    public InvalidNumberException(string message) : base(message) { }
    public InvalidNumberException(string message, System.Exception inner) : base(message, inner) { }

    // A constructor is needed for serialization when an
    // exception propagates from a remoting server to the client. 
    protected InvalidNumberException(System.Runtime.Serialization.SerializationInfo info,
        System.Runtime.Serialization.StreamingContext context) { }
}

but I don't know how to implement the method or constructor in this class that a number entered from the console is equal to 5, and if it is not, it throws an exception.

I'll appreciate if someone helps me with this.


The exception itself shouldn't do the checking. Instead, whatever code you have that works with the number should do this. Try something like this:

if (number == 5)
    throw new InvalidNumberException();


You don't need all those constructors. Think about the exception you are creating - to ensure an int is != to 5.

So, I would have a single constructor like this:

public InvalidNumberException(int value)
    : base(String.Format("Some custom error message. Value: {0}", value)) { }

And use it like this:

if (number == 5)
    throw new InvalidNumberException(number);

You shouldn't be wrapping that in a try block. It's the job of the code that executes the above code block to watch for exceptions, e.g:

try
{
    CallSomeMethodWhichChecksTheNumberAndThrowsIfNecessary();
}
catch (InvalidNumberException inex)
{
    // do something, print to console, log, etc
}

I'm hoping this is just for learning because there is the Int32.Parse and Int32.TryParse methods for this purpose - a custom exception class is not required.


The accepted answer is wrong!

From the accepted answer:

public InvalidNumberException(int value)
{
   var message = string.Format("Some custom error message. Value: {0}", value);
   base(message, this.InnerException)
}

This is a better way to do it:

public InvalidNumberException(int value) : base(string.Format("Some custom error message. Value: {0}", value)) { }


By throwing an exception it is implied that your program at some given circumstances says that it cannot execute normally and must abort. You do it like so:

if (conditionMet)
    throw new Exception();

To be more specific, you can use more specific exceptions like InvalidOperationException, NullReferenceException, etc. Sometimes you might want to use even more specific exception and that's when you create your own Exception type by deriving from the base System.Exception. Think of the custom exception you create as a container for the condition your program had. In your case the condition is that an invalid number has been passed, so you create an InvalidNumberException container which you use instead of the generic Exception above.

Whenever the CLR executes your "throw new" statement it will abort the execution of the current code path and will look for catch statements that can handle that exception.

So your code could look like:

try
{
    if (number == 5)
        throw new InvalidNumberException();
}
catch (InvalidNumberException e)
{
   System.Console.WriteLine("Hey I got an InvalidNumberException");
}


It is not necessarily true that all thrown exceptions are for errors that will lead to aborting your app - as long as they are caught without percolating up, that is ;).

In the case of an invalid number entry, you might receive the exception and then prompt the user that he has entered an invalid number, note the rules on valid numbers, and ask him or her to re-enter the number. The same is true if the user entered a misspelled password or connection string for the database account and caught a SqlException, or for a hundred other correctable mistakes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜