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. Show
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support. Exception Class
DefinitionRepresents errors that occur during application execution. In this articlepublic 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[ExamplesThe 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. // atRemarksThis 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 Errors and exceptionsRun-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.
Try/catch blocksThe common language runtime provides an exception handling model that is based on the representation of exceptions as objects, and the separation of program code and exception handling code into try blocks and catch blocks. There can be one or more catch blocks, each designed to handle a particular type of exception, or one block designed to catch a more specific exception than another block. If an application handles exceptions that occur during the execution of a block of application code, the code must be placed within a try statement and is called a try block. Application code that handles exceptions thrown by a try block is placed within a catch statement and is called a catch block. Zero or more catch blocks are associated with a try block, and each catch block includes a type filter that determines the types of exceptions it handles. When an exception occurs in a try block, the system searches the associated catch blocks in the order they appear in application code, until it locates a catch block that handles the exception. A catch block handles an exception of type T if the type filter of the catch block specifies T or any type that T derives from. The system stops searching after it finds the first catch block that handles the exception. For this reason, in application code, a catch block that handles a type must be specified before a catch block that handles its base types, as demonstrated in the example that follows this section. A catch block that handles System.Exception is specified last. If none of the catch blocks associated with the current try block handle the exception, and the current try block is nested within other try blocks in the current call, the catch blocks associated with the next enclosing try block are searched. If no catch block for the exception is found, the system searches previous nesting levels in the current call. If no catch block for the exception is found in the current call, the exception is passed up the call stack, and the previous stack frame is searched for a catch block that handles the exception. The search of the call stack continues until the exception is handled or until no more frames exist on the call stack. If the top of the call stack is reached without finding a catch block that handles the exception, the default exception handler handles it and the application terminates. F# try..with ExpressionF# does not use catch blocks. Instead, a raised exception is pattern matched using a single with block. As this is an expression, rather than a statement, all paths must return the same type. To learn more, see The try...with Expression. Exception type featuresException types support the following features:
Exception class propertiesThe Exception class includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: StackTrace, InnerException, Message, HelpLink, HResult, Source, TargetSite, and Data. When a causal relationship exists between two or more exceptions, the InnerException property maintains this information. The outer exception is thrown in response to this inner exception. The code that handles the outer exception can use the information from the earlier inner exception to handle the error more appropriately. Supplementary information about the exception can be stored as a collection of key/value pairs in the Data property. The error message string that is passed to the constructor during the creation of the exception object should be localized and can be supplied from a resource file by using the ResourceManager class. For more information about localized resources, see the Creating Satellite Assemblies and Packaging and Deploying Resources topics. To provide the user with extensive information about why the exception occurred, the HelpLink property can hold a URL (or URN) to a help file. The Exception class uses the HRESULT COR_E_EXCEPTION, which has the value 0x80131500. For a list of initial property values for an instance of the Exception class, see the Exception constructors. Performance considerationsThrowing or handling an exception consumes a significant amount of system resources and execution time. Throw exceptions only to handle truly extraordinary conditions, not to handle predictable events or flow control. For example, in some cases, such as when you're developing a class library, it's reasonable to throw an exception if a method argument is invalid, because you expect your method to be called with valid parameters. An invalid method argument, if it is not the result of a usage error, means that something extraordinary has occurred. Conversely, do not throw an exception if user input is invalid, because you can expect users to occasionally enter invalid data. Instead, provide a retry mechanism so users can enter valid input. Nor should you use exceptions to handle usage errors. Instead, use assertions to identify and correct usage errors. In addition, do not throw an exception when a return code is sufficient; do not convert a return code to an exception; and do not routinely catch an exception, ignore it, and then continue processing. Re-throwing an exceptionIn many cases, an exception handler simply wants to pass the exception on to the caller. This most often occurs in:
The recommended way to re-throw an exception is to simply use the throw statement in C#, the reraise function in F#, and the Throw statement in Visual Basic without including an expression. This ensures that all call stack information is preserved when the exception is propagated to the caller. The following example illustrates this. A string extension method, FindOccurrences, wraps one or more calls to String.IndexOf(String, Int32) without validating its arguments beforehand. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; public static class Library { public static int[] FindOccurrences(this String s, String f) { var indexes = new ListA caller then calls FindOccurrences twice. In the second call to FindOccurrences, the caller passes a null as the search string, which causes the String.IndexOf(String, Int32) method to throw an ArgumentNullException exception. This exception is handled by the FindOccurrences method and passed back to the caller. Because the throw statement is used with no expression, the output from the example shows that the call stack is preserved. public class Example { public static void Main() { String s = "It was a cold day when..."; int[] indexes = s.FindOccurrences("a"); ShowOccurrences(s, "a", indexes); Console.WriteLine(); String toFind = null; 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}\n", e.Message); Console.WriteLine("Stack Trace:\n {0}\n", e.StackTrace); } } private static void ShowOccurrences(String s, String toFind, int[] indexes) { Console.Write("'{0}' occurs at the following character positions: ", toFind); for (int ctr = 0; ctr < indexes.Length; ctr++) Console.Write("{0}{1}", indexes[ctr], ctr == indexes.Length - 1 ? "" : ", "); Console.WriteLine(); } } // 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() open Library let showOccurrences toFind (indexes: int[]) = printf $"'{toFind}' occurs at the following character positions: " for i = 0 to indexes.Length - 1 do printf $"""{indexes[i]}{if i = indexes.Length - 1 then "" else ", "}""" printfn "" let s = "It was a cold day when..." let indexes = findOccurrences s "a" showOccurrences "a" indexes printfn "" let toFind: string = null 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}\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) // atIn contrast, if the exception is re-thrown by using the throw e; Throw e raise estatement, the full call stack is not preserved, and the example would generate the following output: 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 exceptionsWhen 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:
The following table lists common exception types and the conditions under which you would throw them.
Implementing custom exceptionsIn the following cases, using an existing .NET Framework exception to handle an error condition is not adequate:
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:
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 [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. The following example makes two calls to the GetPrimesFrom method with non-prime numbers, one of which crosses application domain boundaries. In both cases, the exception is thrown and successfully handled in client code. using System; using System.Reflection; class Example { public static void Main() { int limit = 10000000; PrimeNumberGenerator primes = new PrimeNumberGenerator(limit); int start = 1000001; try { int[] values = primes.GetPrimesFrom(start); Console.WriteLine("There are {0} prime numbers from {1} to {2}", start, limit); } catch (NotPrimeException e) { Console.WriteLine("{0} is not prime", e.NonPrime); Console.WriteLine(e); Console.WriteLine("--------"); } AppDomain domain = AppDomain.CreateDomain("Domain2"); PrimeNumberGenerator gen = (PrimeNumberGenerator)domain.CreateInstanceAndUnwrap( typeof(Example).Assembly.FullName, "PrimeNumberGenerator", true, BindingFlags.Default, null, new object[] { 1000000 }, null, null); try { start = 100; Console.WriteLine(gen.GetPrimesFrom(start)); } catch (NotPrimeException e) { Console.WriteLine("{0} is not prime", e.NonPrime); Console.WriteLine(e); Console.WriteLine("--------"); } } } open System open System.Reflection let limit = 10000000 let primes = PrimeNumberGenerator limit let start = 1000001 try let values = primes.GetPrimesFrom start printfn $"There are {values.Length} prime numbers from {start} to {limit}" with :? NotPrimeException as e -> printfn $"{e.NonPrime} is not prime" printfn $"{e}" printfn "--------" let domain = AppDomain.CreateDomain "Domain2" let gen = domain.CreateInstanceAndUnwrap( typeofWindows Runtime and .NET Framework 4.5.1In .NET for Windows 8.x Store apps for Windows 8, some exception information is typically lost when an exception is propagated through non-.NET Framework stack frames. Starting with the .NET Framework 4.5.1 and Windows 8.1, the common language runtime continues to use the original Exception object that was thrown unless that exception was modified in a non-.NET Framework stack frame. ConstructorsProperties
Methods
Events
Applies toSee also
Which of the following method of String class is most appropriate for extracting all the characters of String into an array?Explanation: Because we are performing operation on reference variable which is null. 5. Which of these methods can be used to convert all characters in a String into a character array? Explanation: charAt() return one character only not array of character.
Which one of the following methods converts all Java objects into String objects?We can convert Object to String in java using toString() method of Object class or String. valueOf(object) method. You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else.
Which of the following methods will create String in Java Mcq?The intern() and toString() methods are of String class.
Which of the following method is used to convert a String into an array?We can also convert String to String array by using the toArray() method of the List class. It takes a list of type String as the input and converts each entity into a string array.
|