When your program throws an exception, you can use a try-catch-finally
block to catch the exception and examine it to determine its class. When you want to throw your own exception, however, you must know what exception classes are available so that you can pick the best one to throw. The following sections describe some of the most useful classes for throwing exceptions.
The following table lists some of the most useful exception classes in C#. If possible you should use one of these standard classes when you need to throw an exception.
Class | Purpose |
AmbiguousMatchException | The program could not figure out which overloaded object method to use. |
ArgumentException | An argument is invalid. |
ArgumentNullException | An argument that cannot be null has the value null . |
ArgumentOutOfRangeException | An argument is out of its allowed range. |
ArithmeticException | An arithmetic, casting, or conversion operation has occurred. |
ArrayTypeMismatchException | The program tried to store the wrong type of item in an array. |
ConfigurationException | A configuration setting is invalid. |
ConstraintException | A data operation violates a database constraint. |
DataException | The ancestor class for ADO.NET exception classes. |
DirectoryNotFoundException | A needed directory is missing. |
DivideByZeroException | The program tried to divide by zero. |
DuplicateNameException | An ADO.NET operation encountered a duplicate name. For example, it tried to create two tables with the same name. |
EvaluateException | Occurs when a DataColumn ’s Expression property cannot be evaluated. |
FieldAccessException | The program tried to access a class property improperly. |
FormatException | An argument doesn’t match its required format. |
IndexOutOfRangeException | The program tried to access an item outside of the bounds of an array or other container. |
InvalidCastException | The program tried to make an invalid conversion. For example, int.Parse("ten") . |
InvalidOperationException | The operation is not currently allowed. |
IOException | The ancestor class for input/output (I/O) exception classes. A generic I/O error occurred. |
EndOfStreamException | A stream reached its end. |
FileLoadException | Error loading a file. |
FileNotFoundException | Error finding a file. |
InternalBufferOverflow Exception | An internal buffer overflowed. |
MemberAccessException | The program tried to access a class member improperly. |
MethodAccessException | The program tried to access a class method improperly. |
MissingFieldException | The program tried to access a class field that doesn’t exist. |
MissingMemberException | The program tried to access a class member that doesn’t exist. |
MissingMethodException | The program tried to access a class method that doesn’t exist. |
NotFiniteNumberException | A floating-point number is PositiveInfinity , NegativeInfinity , or NaN (Not a Number). You can get these values from the floating-point classes (as in float.NaN or double.PositiveInfinity ). |
NotImplementedException | The requested operation is not implemented. |
NotSupportedException | The requested operation is not supported. For example, the program might be asking a routine to modify data that was opened as read-only. |
NullReferenceException | The program tried to use an object reference that is null . |
OutOfMemoryException | There isn’t enough memory. Note that sometimes a program cannot recover from an OutOfMemoryException because it doesn’t have enough memory to do anything useful. |
OverflowException | An arithmetic, casting, or conversion operation created an overflow. For example, the program tried to assign a large int value to a byte variable. |
PolicyException | Policy prevents the code from running. |
RankException | A routine is trying to use an array with the wrong number of dimensions. |
ReadOnlyException | The program tried to modify read-only data. |
SecurityException | A security violation occurred. |
SyntaxErrorException | A DataColumn ’s Expression property contains invalid syntax. |
UnauthorizedAccessException | The system is denying access because of an I/O or security error. |
Use the throw
statement to throw an exception. The following code throws a DivideByZeroException
.
throw new DivideByZeroException("No employees are defined.");
This code passes the exception class’s constructor a message describing the exception. In this case, the divide by zero exception occurred because the application did not have any employees defined. Notice that the message explains the reason for the exception, not just the fact that a division by zero occurred.
To define a custom exception class, make a class that inherits from the Exception
class. To give developers who use the class the most flexibility, provide four constructors that delegate their work to the parent class’s corresponding constructors.
The following code shows the InvalidWorkAssignmentException
class. The parameterless constructor passes the Exception
class’s constructor a default error message. The other constructors simply pass their arguments to the Exception
class’s other constructors.
public class InvalidWorkAssignmentException : Exception
{
public InvalidWorkAssignmentException()
: base("This work assignment is invalid")
{
}
public InvalidWorkAssignmentException(string message)
: base(message)
{
}
public InvalidWorkAssignmentException(string message, Exception innerException)
: base(message, innerException)
{
}
public InvalidWorkAssignmentException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
}
For more information on custom exception classes, see the section “Custom Exceptions” in Chapter 9, “Error Handing.” Also see the online documentation for topics such as “Designing Custom Exceptions” (msdn.microsoft.com/library/vstudio/ms229064(v=vs.100).aspx) and “Design Guidelines for Exceptions” (msdn.microsoft.com/ms229014.aspx).