Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to create an own exception in C#?

example suppose i want entered age must be in positive number if user enter negative value then it must throw an exception of negative number exeption.



and also what is the basic use of throw keyword in C#?
Posted
Updated 13-Mar-13 21:49pm
v5
Comments
Orcun Iyigun 14-Mar-13 5:18am    
Another option instead of throwing an exception is: If it is win forms you can disable "-" in key press event. If it is in web you can use filteredtextboxextender to not to allow "-" chaacter.
Ian A Davidson 14-Mar-13 7:48am    
What do you mean by "basic use of throw keyword"?
You throw an exception using it :) E.g. "throw new ArgumentException("paramName");"
Or you can rethrow an exception from a catch block simply by using "throw;" e.g. after doing something with or to the exception:
catch(Exception e)
{
/* Log error or add data to the exception, for example e.Data.Add("MyInfo", info); */
throw;
}

In your scenario I suggest you to use ArgumentOutOfRangeException[^] (derived from ArgumentException[^]), which should be thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.
 
Share this answer
 
v2
Comments
Ian A Davidson 14-Mar-13 7:39am    
I think I'd go for this option myself - provided that the value being tested is indeed a parameter of the method in which the exception is being raised.
Matt T Heffron 15-Mar-13 18:01pm    
And if it is NOT a parameter, the InvalidOperationException is appropriate.
Code

C#
try
            {
                int i = -1;
                if (i < 0)
                {
                    throw new NegativeNumberException("Error");
                }
            }
            catch (NegativeNumberException nx)
            {
                MessageBox.Show(nx.Message);
            }


User Defined Exception

C#
public class NegativeNumberException : System.Exception
    {
        public NegativeNumberException()
        {
        }

        public NegativeNumberException(string message)
            : base(message)
        {
        }

        public NegativeNumberException(string message, System.Exception innerException)
            : base(message, innerException)
        {
        }
    }
 
Share this answer
 
Comments
Ian A Davidson 14-Mar-13 7:35am    
Good answer. However, one point you might like to take note of yourself: Your Exception class should be serialisable - i.e. have the Serializable attribute and implement the constructor that takes SerializationInfo and StreamingContext parameters.
Also, you probalby ought to seal this class since it is highly unlikely you will derive from it (in fact it is good practice to seal every class you develop in the first instance, unless you are sure you are going to derive from it, or explicitly want to allow others to derive from it). I.e. declare it "[Serializable] public sealed class NegativeNumberException : Exception" ... and add the constructor "public NegativeNumberException(SerializationInfo info, StreamingContext context) : base(info, context) {} "
Renju Vinod 14-Mar-13 8:04am    
@Ian A Davidson : Thankz
Write a class derived from the Exception class and implement your required logic in it

Custom exceptions in C#.NET[^]
 
Share this answer
 
Comments
Ian A Davidson 14-Mar-13 7:37am    
Could you clarify what you mean by implementing the required logic IN the exception?
bbirajdar 14-Mar-13 7:42am    
That means - the custom error message to be thrown by default and anything else like logging the error etc. can be done inside the derived class. You will then not need to wriet the same code everwhere
Ian A Davidson 14-Mar-13 7:51am    
Okay I see. I thought you meant doing the check for the negative number :)
Your class looks good. I like the constructor that takes parameters to be formatted.
Exception is the used to handle the error.

You can handle the error using the try catch.

eg;

C#
try
{
  //real code for your task.....
}

catch (exception ex)
{
  throw ex;
}


In the above code first you try to get the result...
If any error occurred while trying to find the result say connection loss while retrieving the data
then it will catch the error i.e exception and throw the error as the message.
well this is not the way to handle the error.
you can do...

C#
try
{
 //real code for your task...
}

catch (exception ex)
{
  Console.WriteLine(ex.message);
  Console.Read();
}


I hope this will help you...
 
Share this answer
 
Comments
Ian A Davidson 14-Mar-13 7:26am    
You should avoid catching "Exception", and catch derived exceptions that you know how to handle. Having said that, in a very few exceptional cases, I still do catch "Exception" - e.g. in order to simply log the error and then exit the application. However, this is often more down to laziness than anything else. It's not recommended.

Edit: You can catch "Exception" provided you are going to rethrow it. And I mean, rethrow, not create your own exception from it. I.e. "catch(Exception e) { /* Do something with e*/ throw; }
Ian A Davidson 14-Mar-13 8:14am    
http://msdn.microsoft.com/en-us/library/ms182137(v=vs.80).aspx

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900