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:
Code:
using System.Runtime.Serialization;
[Serializable]
public class UserException : ApplicationException
{
public UserException()
{
}
public UserException(string message)
: base(message)
{
}
public UserException(string message, Exception innerException)
: base(message, innerException)
{
}
public UserException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
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:
Code:
[Serializable]
public class UserException<T> : UserException
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:
Code:
[Serializable]
public class MathException : 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.
Attached is a sample code file showing exception classes and handling of exceptions.