Which of the following method simply returns a string that appropriately describes an object of a class?

Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Exception Class

  • Reference

Definition

Represents errors that occur during application execution.

In this article

public ref class Exceptionpublic ref class Exception : System::Runtime::Serialization::ISerializablepublic ref class Exception : System::Runtime::InteropServices::_Exception, System::Runtime::Serialization::ISerializablepublic class Exceptionpublic class Exception : System.Runtime.Serialization.ISerializable[System.Runtime.InteropServices.ClassInterface[System.Runtime.InteropServices.ClassInterfaceType.AutoDual]] [System.Serializable] public class Exception : System.Runtime.Serialization.ISerializable[System.Serializable] [System.Runtime.InteropServices.ClassInterface[System.Runtime.InteropServices.ClassInterfaceType.None]] [System.Runtime.InteropServices.ComVisible[true]] public class Exception : System.Runtime.InteropServices._Exception, System.Runtime.Serialization.ISerializable[System.Serializable] [System.Runtime.InteropServices.ClassInterface[System.Runtime.InteropServices.ClassInterfaceType.None]] [System.Runtime.InteropServices.ComVisible[true]] public class Exception : System.Runtime.Serialization.ISerializabletype Exception = classtype Exception = class interface ISerializable[] [] type Exception = class interface ISerializable[] [] [] type Exception = class interface ISerializable interface _Exception[] [] [] type Exception = class interface ISerializablePublic Class ExceptionPublic Class Exception Implements ISerializablePublic Class Exception Implements _Exception, ISerializableInheritanceDerived AttributesImplements

Examples

The following example demonstrates a catch [with in F#] block that is defined to handle ArithmeticException errors. This catch block also catches DivideByZeroException errors, because DivideByZeroException derives from ArithmeticException and there is no catch block explicitly defined for DivideByZeroException errors.

using namespace System; int main[] { int x = 0; try { int y = 100 / x; } catch [ ArithmeticException^ e ] { Console::WriteLine[ "ArithmeticException Handler: {0}", e ]; } catch [ Exception^ e ] { Console::WriteLine[ "Generic Exception Handler: {0}", e ]; } } /* This code example produces the following results: ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero. at main[] */ using System; class ExceptionTestClass { public static void Main[] { int x = 0; try { int y = 100 / x; } catch [ArithmeticException e] { Console.WriteLine[$"ArithmeticException Handler: {e}"]; } catch [Exception e] { Console.WriteLine[$"Generic Exception Handler: {e}"]; } } } /* This code example produces the following results: ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero. at ExceptionTestClass.Main[] */ module ExceptionTestModule open System let x = 0 try let y = 100 / x [] with | :? ArithmeticException as e -> printfn $"ArithmeticException Handler: {e}" | e -> printfn $"Generic Exception Handler: {e}" // This code example produces the following results: // ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero. // at .$ExceptionTestModule.main@[] Class ExceptionTestClass Public Shared Sub Main[] Dim x As Integer = 0 Try Dim y As Integer = 100 / x Catch e As ArithmeticException Console.WriteLine["ArithmeticException Handler: {0}", e.ToString[]] Catch e As Exception Console.WriteLine["Generic Exception Handler: {0}", e.ToString[]] End Try End Sub End Class ' 'This code example produces the following results: ' 'ArithmeticException Handler: System.OverflowException: Arithmetic operation resulted in an overflow. ' at ExceptionTestClass.Main[] '

Remarks

This class is the base class for all exceptions. When an error occurs, either the system or the currently executing application reports it by throwing an exception that contains information about the error. After an exception is thrown, it is handled by the application or by the default exception handler.

In this section:

Errors and exceptions
Try/catch blocks
Exception type features
Exception class properties
Performance considerations
Re-throwing an exception
Choosing standard exceptions
Implementing custom exceptions

Errors and exceptions

Run-time errors can occur for a variety of reasons. However, not all errors should be handled as exceptions in your code. Here are some categories of errors that can occur at run time and the appropriate ways to respond to them.

  • Usage errors. A usage error represents an error in program logic that can result in an exception. However, the error should be addressed not through exception handling but by modifying the faulty code. For example, the override of the Object.Equals[Object] method in the following example assumes that the obj argument must always be non-null.

    using System; public class Person { private string _name; public string Name { get { return _name; } set { _name = value; } } public override int GetHashCode[] { return this.Name.GetHashCode[]; } public override bool Equals[object obj] { // This implementation contains an error in program logic: // It assumes that the obj argument is not null. Person p = [Person] obj; return this.Name.Equals[p.Name]; } } public class Example { public static void Main[] { Person p1 = new Person[]; p1.Name = "John"; Person p2 = null; // The following throws a NullReferenceException. Console.WriteLine["p1 = p2: {0}", p1.Equals[p2]]; } } // In F#, null is not a valid state for declared types // without 'AllowNullLiteralAttribute' [] type Person[] = member val Name = "" with get, set override this.GetHashCode[] = this.Name.GetHashCode[] override this.Equals[obj] = // This implementation contains an error in program logic: // It assumes that the obj argument is not null. let p = obj :?> Person this.Name.Equals p.Name let p1 = Person[] p1.Name printfn $"An exception [{e.GetType[].Name}] occurred." printfn $"Message:\n {e.Message}\n" printfn $"Stack Trace:\n {e.StackTrace}\n" // The example displays the following output: // 'a' occurs at the following character positions: 4, 7, 15 // // An exception [ArgumentNullException] occurred. // Message: // Value cannot be null. [Parameter 'value'] // // Stack Trace: // at System.String.IndexOf[String value, Int32 startIndex, Int32 count, Stri // ngComparison comparisonType] // at Library.findOccurrences[String s, String f] // at .main@[] Module Example Public Sub Main[] Dim s As String = "It was a cold day when..." Dim indexes[] As Integer = s.FindOccurrences["a"] ShowOccurrences[s, "a", indexes] Console.WriteLine[] Dim toFind As String = Nothing Try indexes = s.FindOccurrences[toFind] ShowOccurrences[s, toFind, indexes] Catch e As ArgumentNullException Console.WriteLine["An exception [{0}] occurred.", e.GetType[].Name] Console.WriteLine["Message:{0} {1}{0}", vbCrLf, e.Message] Console.WriteLine["Stack Trace:{0} {1}{0}", vbCrLf, e.StackTrace] End Try End Sub Private Sub ShowOccurrences[s As String, toFind As String, indexes As Integer[]] Console.Write["'{0}' occurs at the following character positions: ", toFind] For ctr As Integer = 0 To indexes.Length - 1 Console.Write["{0}{1}", indexes[ctr], If[ctr = indexes.Length - 1, "", ", "]] Next Console.WriteLine[] End Sub End Module ' The example displays the following output: ' 'a' occurs at the following character positions: 4, 7, 15 ' ' An exception [ArgumentNullException] occurred. ' Message: ' Value cannot be null. ' Parameter name: value ' ' Stack Trace: ' at System.String.IndexOf[String value, Int32 startIndex, Int32 count, Stri ' ngComparison comparisonType] ' at Library.FindOccurrences[String s, String f] ' at Example.Main[]

    In contrast, if the exception is re-thrown by using the

    throw e; Throw e raise e

    statement, the full call stack is not preserved, and the example would generate the following output:

    'a' occurs at the following character positions: 4, 7, 15 An exception [ArgumentNullException] occurred. Message: Value cannot be null. Parameter name: value Stack Trace: at Library.FindOccurrences[String s, String f] at Example.Main[]

    A slightly more cumbersome alternative is to throw a new exception, and to preserve the original exception's call stack information in an inner exception. The caller can then use the new exception's InnerException property to retrieve stack frame and other information about the original exception. In this case, the throw statement is:

    throw new ArgumentNullException["You must supply a search string.", e]; raise [ArgumentNullException["You must supply a search string.", e] ] Throw New ArgumentNullException["You must supply a search string.", e]

    The user code that handles the exception has to know that the InnerException property contains information about the original exception, as the following exception handler illustrates.

    try { indexes = s.FindOccurrences[toFind]; ShowOccurrences[s, toFind, indexes]; } catch [ArgumentNullException e] { Console.WriteLine["An exception [{0}] occurred.", e.GetType[].Name]; Console.WriteLine[" Message:\n{0}", e.Message]; Console.WriteLine[" Stack Trace:\n {0}", e.StackTrace]; Exception ie = e.InnerException; if [ie != null] { Console.WriteLine[" The Inner Exception:"]; Console.WriteLine[" Exception Name: {0}", ie.GetType[].Name]; Console.WriteLine[" Message: {0}\n", ie.Message]; Console.WriteLine[" Stack Trace:\n {0}\n", ie.StackTrace]; } } // The example displays the following output: // 'a' occurs at the following character positions: 4, 7, 15 // // An exception [ArgumentNullException] occurred. // Message: You must supply a search string. // // Stack Trace: // at Library.FindOccurrences[String s, String f] // at Example.Main[] // // The Inner Exception: // Exception Name: ArgumentNullException // Message: Value cannot be null. // Parameter name: value // // Stack Trace: // at System.String.IndexOf[String value, Int32 startIndex, Int32 count, Stri // ngComparison comparisonType] // at Library.FindOccurrences[String s, String f] try let indexes = findOccurrences s toFind showOccurrences toFind indexes with :? ArgumentNullException as e -> printfn $"An exception [{e.GetType[].Name}] occurred." printfn $" Message:\n{e.Message}" printfn $" Stack Trace:\n {e.StackTrace}" let ie = e.InnerException if ie null then printfn " The Inner Exception:" printfn $" Exception Name: {ie.GetType[].Name}" printfn $" Message: {ie.Message}\n" printfn $" Stack Trace:\n {ie.StackTrace}\n" // The example displays the following output: // 'a' occurs at the following character positions: 4, 7, 15 // // An exception [ArgumentNullException] occurred. // Message: You must supply a search string. // // Stack Trace: // at Library.FindOccurrences[String s, String f] // at Example.Main[] // // The Inner Exception: // Exception Name: ArgumentNullException // Message: Value cannot be null. // Parameter name: value // // Stack Trace: // at System.String.IndexOf[String value, Int32 startIndex, Int32 count, Stri // ngComparison comparisonType] // at Library.FindOccurrences[String s, String f] Try indexes = s.FindOccurrences[toFind] ShowOccurrences[s, toFind, indexes] Catch e As ArgumentNullException Console.WriteLine["An exception [{0}] occurred.", e.GetType[].Name] Console.WriteLine[" Message: {1}{0}", vbCrLf, e.Message] Console.WriteLine[" Stack Trace:{0} {1}{0}", vbCrLf, e.StackTrace] Dim ie As Exception = e.InnerException If ie IsNot Nothing Then Console.WriteLine[" The Inner Exception:"] Console.WriteLine[" Exception Name: {0}", ie.GetType[].Name] Console.WriteLine[" Message: {1}{0}", vbCrLf, ie.Message] Console.WriteLine[" Stack Trace:{0} {1}{0}", vbCrLf, ie.StackTrace] End If End Try ' The example displays the following output: ' 'a' occurs at the following character positions: 4, 7, 15 ' ' An exception [ArgumentNullException] occurred. ' Message: You must supply a search string. ' ' Stack Trace: ' at Library.FindOccurrences[String s, String f] ' at Example.Main[] ' ' The Inner Exception: ' Exception Name: ArgumentNullException ' Message: Value cannot be null. ' Parameter name: value ' ' Stack Trace: ' at System.String.IndexOf[String value, Int32 startIndex, Int32 count, Stri ' ngComparison comparisonType] ' at Library.FindOccurrences[String s, String f]

    Choosing standard exceptions

    When you have to throw an exception, you can often use an existing exception type in the .NET Framework instead of implementing a custom exception. You should use a standard exception type under these two conditions:

    • You are throwing an exception that is caused by a usage error [that is, by an error in program logic made by the developer who is calling your method]. Typically, you would throw an exception such as ArgumentException, ArgumentNullException, InvalidOperationException, or NotSupportedException. The string you supply to the exception object's constructor when instantiating the exception object should describe the error so that the developer can fix it. For more information, see the Message property.

    • You are handling an error that can be communicated to the caller with an existing .NET Framework exception. You should throw the most derived exception possible. For example, if a method requires an argument to be a valid member of an enumeration type, you should throw an InvalidEnumArgumentException [the most derived class] rather than an ArgumentException.

    The following table lists common exception types and the conditions under which you would throw them.

    ExceptionCondition
    ArgumentException A non-null argument that is passed to a method is invalid.
    ArgumentNullException An argument that is passed to a method is null.
    ArgumentOutOfRangeException An argument is outside the range of valid values.
    DirectoryNotFoundException Part of a directory path is not valid.
    DivideByZeroException The denominator in an integer or Decimal division operation is zero.
    DriveNotFoundException A drive is unavailable or does not exist.
    FileNotFoundException A file does not exist.
    FormatException A value is not in an appropriate format to be converted from a string by a conversion method such as Parse.
    IndexOutOfRangeException An index is outside the bounds of an array or collection.
    InvalidOperationException A method call is invalid in an object's current state.
    KeyNotFoundException The specified key for accessing a member in a collection cannot be found.
    NotImplementedException A method or operation is not implemented.
    NotSupportedException A method or operation is not supported.
    ObjectDisposedException An operation is performed on an object that has been disposed.
    OverflowException An arithmetic, casting, or conversion operation results in an overflow.
    PathTooLongException A path or file name exceeds the maximum system-defined length.
    PlatformNotSupportedException The operation is not supported on the current platform.
    RankException An array with the wrong number of dimensions is passed to a method.
    TimeoutException The time interval allotted to an operation has expired.
    UriFormatException An invalid Uniform Resource Identifier [URI] is used.

    Implementing custom exceptions

    In the following cases, using an existing .NET Framework exception to handle an error condition is not adequate:

    • When the exception reflects a unique program error that cannot be mapped to an existing .NET Framework exception.

    • When the exception requires handling that is different from the handling that is appropriate for an existing .NET Framework exception, or the exception must be disambiguated from a similar exception. For example, if you throw an ArgumentOutOfRangeException exception when parsing the numeric representation of a string that is out of range of the target integral type, you would not want to use the same exception for an error that results from the caller not supplying the appropriate constrained values when calling the method.

    The Exception class is the base class of all exceptions in the .NET Framework. Many derived classes rely on the inherited behavior of the members of the Exception class; they do not override the members of Exception, nor do they define any unique members.

    To define your own exception class:

    1. Define a class that inherits from Exception. If necessary, define any unique members needed by your class to provide additional information about the exception. For example, the ArgumentException class includes a ParamName property that specifies the name of the parameter whose argument caused the exception, and the RegexMatchTimeoutException property includes a MatchTimeout property that indicates the time-out interval.

    2. If necessary, override any inherited members whose functionality you want to change or modify. Note that most existing derived classes of Exception do not override the behavior of inherited members.

    3. Determine whether your custom exception object is serializable. Serialization enables you to save information about the exception and permits exception information to be shared by a server and a client proxy in a remoting context. To make the exception object serializable, mark it with the SerializableAttribute attribute.

    4. Define the constructors of your exception class. Typically, exception classes have one or more of the following constructors:

      • Exception[], which uses default values to initialize the properties of a new exception object.

      • Exception[String], which initializes a new exception object with a specified error message.

      • Exception[String, Exception], which initializes a new exception object with a specified error message and inner exception.

      • Exception[SerializationInfo, StreamingContext], which is a protected constructor that initializes a new exception object from serialized data. You should implement this constructor if you've chosen to make your exception object serializable.

    The following example illustrates the use of a custom exception class. It defines a NotPrimeException exception that is thrown when a client tries to retrieve a sequence of prime numbers by specifying a starting number that is not prime. The exception defines a new property, NonPrime, that returns the non-prime number that caused the exception. Besides implementing a protected parameterless constructor and a constructor with SerializationInfo and StreamingContext parameters for serialization, the NotPrimeException class defines three additional constructors to support the NonPrime property. Each constructor calls a base class constructor in addition to preserving the value of the non-prime number. The NotPrimeException class is also marked with the SerializableAttribute attribute.

    using System; using System.Runtime.Serialization; [Serializable[]] public class NotPrimeException : Exception { private int notAPrime; protected NotPrimeException[] : base[] { } public NotPrimeException[int value] : base[String.Format["{0} is not a prime number.", value]] { notAPrime = value; } public NotPrimeException[int value, string message] : base[message] { notAPrime = value; } public NotPrimeException[int value, string message, Exception innerException] : base[message, innerException] { notAPrime = value; } protected NotPrimeException[SerializationInfo info, StreamingContext context] : base[info, context] { } public int NonPrime { get { return notAPrime; } } } namespace global open System open System.Runtime.Serialization [] type NotPrimeException = inherit Exception val notAPrime: int member this.NonPrime = this.notAPrime new [value] = { inherit Exception[$"%i{value} is not a prime number."]; notAPrime = value } new [value, message] = { inherit Exception[message]; notAPrime = value } new [value, message, innerException: Exception] = { inherit Exception[message, innerException]; notAPrime = value } // F# does not support protected members new [] = { inherit Exception[]; notAPrime = 0 } new [info: SerializationInfo, context: StreamingContext] = { inherit Exception[info, context]; notAPrime = 0 } Imports System.Runtime.Serialization _ Public Class NotPrimeException : Inherits Exception Private notAPrime As Integer Protected Sub New[] MyBase.New[] End Sub Public Sub New[value As Integer] MyBase.New[String.Format["{0} is not a prime number.", value]] notAPrime = value End Sub Public Sub New[value As Integer, message As String] MyBase.New[message] notAPrime = value End Sub Public Sub New[value As Integer, message As String, innerException As Exception] MyBase.New[message, innerException] notAPrime = value End Sub Protected Sub New[info As SerializationInfo, context As StreamingContext] MyBase.New[info, context] End Sub Public ReadOnly Property NonPrime As Integer Get Return notAPrime End Get End Property End Class

    The PrimeNumberGenerator class shown in the following example uses the Sieve of Eratosthenes to calculate the sequence of prime numbers from 2 to a limit specified by the client in the call to its class constructor. The GetPrimesFrom method returns all prime numbers that are greater than or equal to a specified lower limit, but throws a NotPrimeException if that lower limit is not a prime number.

    using System; using System.Collections.Generic; [Serializable] public class PrimeNumberGenerator { private const int START = 2; private int maxUpperBound = 10000000; private int upperBound; private bool[] primeTable; private List primes = new List[]; public PrimeNumberGenerator[int upperBound] { if [upperBound > maxUpperBound] { string message = String.Format[ "{0} exceeds the maximum upper bound of {1}.", upperBound, maxUpperBound]; throw new ArgumentOutOfRangeException[message]; } this.upperBound = upperBound; // Create array and mark 0, 1 as not prime [True]. primeTable = new bool[upperBound + 1]; primeTable[0] = true; primeTable[1] = true; // Use Sieve of Eratosthenes to determine prime numbers. for [int ctr = START; ctr value == prime]; if [start < 0] throw new NotPrimeException[prime, String.Format["{0} is not a prime number.", prime]]; else return primes.FindAll[[value] => value >= prime].ToArray[]; } } namespace global open System [] type PrimeNumberGenerator[upperBound] = let start = 2 let maxUpperBound = 10000000 let primes = ResizeArray[] let primeTable = upperBound + 1 |> Array.zeroCreate do if upperBound > maxUpperBound then let message = $"{upperBound} exceeds the maximum upper bound of {maxUpperBound}." raise [ArgumentOutOfRangeException message] // Create array and mark 0, 1 as not prime [True]. primeTable[0] ceil |> int do if not primeTable[i] then for multiplier = i to upperBound / i do if i * multiplier Seq.toArray Imports System.Collections.Generic Public Class PrimeNumberGenerator Private Const START As Integer = 2 Private maxUpperBound As Integer = 10000000 Private upperBound As Integer Private primeTable[] As Boolean Private primes As New List[Of Integer] Public Sub New[upperBound As Integer] If upperBound > maxUpperBound Then Dim message As String = String.Format[ "{0} exceeds the maximum upper bound of {1}.", upperBound, maxUpperBound] Throw New ArgumentOutOfRangeException[message] End If Me.upperBound = upperBound ' Create array and mark 0, 1 as not prime [True]. ReDim primeTable[upperBound] primeTable[0] = True primeTable[1] = True ' Use Sieve of Eratosthenes to determine prime numbers. For ctr As Integer = START To CInt[Math.Ceiling[Math.Sqrt[upperBound]]] If primeTable[ctr] Then Continue For For multiplier As Integer = ctr To CInt[upperBound \ ctr] If ctr * multiplier

Chủ Đề