I would like someone to help me understand the process of throwing and handling exceptions based on the following questions. If I create a class pizza that has two fields and a get method for each field that throws a exception relative to each field. Do I have to create a xxxxexception class? If I do is this example close to what the class should look like:
public xxxxexception class
public string name
public int number
public xxxxexception (string name,int number)
I'm really confused
You've got several options. You could certainly create an exception class for each kind of exception you want to throw. You could create an exception class that held an enumeration that you could check to see what was thrown (I wouldn't, though; it's easier to catch derived classes of exceptions). You could create a generic exception class for catching any exception thrown by a specific class. It really depends on what you need to do.
If you're planning on using exceptions, you should decide which of the above best fits your needs. For example, is it more important for you to catch all exceptions generated by one class or to catch one kind of exception generated by any class? It's two different kinds of hierarchy that can't be easily merged.
In general, all you need to do to create an exception class is derive from either Exception or ApplicationException and provide a few constructors. For example:
If you'd like to catch exceptions based on the class that threw it, you can create one generic exception class to handle all of them. It's exactly the same as the above except for the declaration:
public class UserException : ApplicationException
public UserException(string message)
public UserException(string message, Exception innerException)
: base(message, innerException)
public UserException(SerializationInfo info, StreamingContext context)
: base(info, context)
Instead, if you want exceptions based on the action taken to throw it, all you have to do is derive your type of exception from your UserException and create the same old constructors as before:
public class UserException<T> : UserException
The reason it's difficult to have it both ways is that C# doesn't allow multiple inheritance. For example, if I wanted to have a generic MathException class, I'd want to derive it from both the generic UserException and the regular MathException classes. Since C# doesn't allow that, you have to choose one or the other.
public class MathException : UserException
Attached is a sample code file showing exception classes and handling of exceptions.