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 creating 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With