Appendix O
Useful Exception Classes

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.

Standard Exception Classes

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.

ClassPurpose
AmbiguousMatchExceptionThe program could not figure out which overloaded object method to use.
ArgumentExceptionAn argument is invalid.
ArgumentNullExceptionAn argument that cannot be null has the value null.
ArgumentOutOfRangeExceptionAn argument is out of its allowed range.
ArithmeticExceptionAn arithmetic, casting, or conversion operation has occurred.
ArrayTypeMismatchExceptionThe program tried to store the wrong type of item in an array.
ConfigurationExceptionA configuration setting is invalid.
ConstraintExceptionA data operation violates a database constraint.
DataExceptionThe ancestor class for ADO.NET exception classes.
DirectoryNotFoundExceptionA needed directory is missing.
DivideByZeroExceptionThe program tried to divide by zero.
DuplicateNameExceptionAn ADO.NET operation encountered a duplicate name. For example, it tried to create two tables with the same name.
EvaluateExceptionOccurs when a DataColumn’s Expression property cannot be evaluated.
FieldAccessExceptionThe program tried to access a class property improperly.
FormatExceptionAn argument doesn’t match its required format.
IndexOutOfRangeExceptionThe program tried to access an item outside of the bounds of an array or other container.
InvalidCastExceptionThe program tried to make an invalid conversion. For example, int.Parse("ten").
InvalidOperationExceptionThe operation is not currently allowed.
IOExceptionThe ancestor class for input/output (I/O) exception classes. A generic I/O error occurred.
EndOfStreamExceptionA stream reached its end.
FileLoadExceptionError loading a file.
FileNotFoundExceptionError finding a file.
InternalBufferOverflow
­Exception
An internal buffer overflowed.
MemberAccessExceptionThe program tried to access a class member improperly.
MethodAccessExceptionThe program tried to access a class method improperly.
MissingFieldExceptionThe program tried to access a class field that doesn’t exist.
MissingMemberExceptionThe program tried to access a class member that doesn’t exist.
MissingMethodExceptionThe program tried to access a class method that doesn’t exist.
NotFiniteNumberExceptionA 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).
NotImplementedExceptionThe requested operation is not implemented.
NotSupportedExceptionThe requested operation is not supported. For example, the program might be asking a routine to modify data that was opened as read-only.
NullReferenceExceptionThe program tried to use an object reference that is null.
OutOfMemoryExceptionThere 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.
OverflowExceptionAn arithmetic, casting, or conversion operation created an overflow. For example, the program tried to assign a large int value to a byte variable.
PolicyExceptionPolicy prevents the code from running.
RankExceptionA routine is trying to use an array with the wrong number of dimensions.
ReadOnlyExceptionThe program tried to modify read-only data.
SecurityExceptionA security violation occurred.
SyntaxErrorExceptionA DataColumn’s Expression property contains invalid syntax.
UnauthorizedAccessExceptionThe 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.

Custom Exception Classes

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).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.56.45