User Tools

Site Tools


notes:csharp:exceptions

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
notes:csharp:exceptions [2016/07/18]
admin
notes:csharp:exceptions [2016/11/28] (current)
admin [References]
Line 1: Line 1:
 ====== Exceptions in C# ====== ====== Exceptions in C# ======
  
-Exception types suitable for use in custom applications:​ +A minimal custom exception definition:
- +
-| Exception | The base class for all exceptions. Throw a more specific type of exception rather than this one. | +
-| ArgumentException | Throw this exception when an argument to your method is invalid. | +
-| ArgumentNullException | A specialized form of ArgumentException that you can throw when one of your arguments is null and this isn't allowed. | +
-| ArgumentOutOfRangeException | A specialized form of ArgumentException that you can throw when an argument is outside the allowable range of values. | +
-| FormatException | Throw this exception when an argument does not have a valid format. | +
-| InvalidOperationException | Throw this exception when a method is called that is invalid for the object'​s current state. | +
-| NotImplementedException | This exception is often used in generated code where a method has not been implemented yet. | +
-| NotSupportedException | Throw this exception when a method is invoked that you don't support. | +
-| ObjectDisposedException | Throw when a user of your class tries to access methods when Dispose has already been called. | +
- +
- +
-Exception types that should not be thrown in custom applications:​ +
- +
-| ArithmeticException | A base class for other exceptions that occur during arithmetic operations. | +
-| ArrayTypeMismatchException | Thrown when you want to store an incompatible element inside an array. | +
-| DivideByZeroException | Thrown when you try to divide a value by zero.|  +
-| IndexOutOfRangeException | Thrown when you try to access an array with an index that is less than zero or greater than the size of the array. |  +
-| InvalidCastException | Thrown when you try to cast an element to an incompatible type. |  +
-| NullReferenceException | Thrown when you try to reference an element that is null. |  +
-| OutOfMemoryException | Thrown when creating a new object fails because the CLR doesn'​t have enough memory available. |  +
-| OverflowException | Thrown when an arithmetic operation overflows in a checked context. |  +
-| StackOverflowException | Thrown when the execution stack is full. |  +
-| TypeInitializationException | Thrown when a static constructor throws an exception that is unhandled. | +
- +
- +
-**Example**: ​A minimal custom exception definition:+
 <code csharp> <code csharp>
 public class CustomException : Exception // inherit from Exception rather than from ApplicationException public class CustomException : Exception // inherit from Exception rather than from ApplicationException
Line 39: Line 12:
  
  
-**Example**: ​A custom exception that overrides the //Message// property:+A custom exception that overrides the //Message// property:
 <code csharp> <code csharp>
 public class CustomException : Exception ​ public class CustomException : Exception ​
Line 65: Line 38:
  
  
-**Example**: ​A method that traverses ​all inner exceptions and returns their messages and types:+A method that iterates over all inner exceptions and returns their messages and types:
 <code csharp> <code csharp>
 public string GetExceptionDesc(Exception exc) public string GetExceptionDesc(Exception exc)
Line 94: Line 67:
  
  
-**Example**: ​A custom exception that implements //​ISerializable//:​+A custom exception that implements //​ISerializable//:​
 <code csharp> <code csharp>
 // The SerializableAttribute ensures that the custom exception ​ // The SerializableAttribute ensures that the custom exception ​
Line 138: Line 111:
  
  
-**Example**: ​An **exception builder** is a helper method that creates and throws exceptions. A method that calls the exception builder is inlined by the compiler ​as opposite to a method that throws exceptions itself:+An **exception builder** is a helper method that creates and throws exceptions. A method that calls the exception builder is inlined by the compiler:
 <code csharp> <code csharp>
 public class CustomException : Exception public class CustomException : Exception
Line 152: Line 125:
     TimeOut     TimeOut
 } }
- 
 ... ...
- 
 // An exception builder method that creates and throws CustomException. // An exception builder method that creates and throws CustomException.
 private static void ThrowException(ErrorCode code) private static void ThrowException(ErrorCode code)
Line 178: Line 149:
     throw new CustomException(message);​     throw new CustomException(message);​
 } }
- 
 ... ...
- 
 // This method builds exceptions using the exception builder. // This method builds exceptions using the exception builder.
 // As it does not use '​throw'​ to throw exceptions, it is inlined by the compiler. // As it does not use '​throw'​ to throw exceptions, it is inlined by the compiler.
Line 192: Line 161:
  
  
-**Example**: ​//​SoapException//​ wrapper:+An example of implementing a //​SoapException//​ wrapper:
 <code csharp> <code csharp>
 using System; using System;
Line 198: Line 167:
 using System.Web.Services.Protocols;​ using System.Web.Services.Protocols;​
 using System.Xml; using System.Xml;
- 
 ... ...
- 
 public class SoapExceptionWrapper public class SoapExceptionWrapper
 { {
Line 254: Line 221:
  
  
-**Example**:​ //​Environment.FailFast//​ and //​ExceptionDispatchInfo.Throw//​:+Exception types that are suitable to throw in custom code:
  
-Preventing the finally block from running can be achieved by using //​Environment.FailFast//This method ​has two overloads: +^ Exception ^ The base class for all exceptionsThrow a more specific type of exception rather than this one
-  ​* ​one that only takes string +| ArgumentException | Throw this exception when an argument to your method ​is invalid. | 
-  * another one that also takes an exception+| ArgumentNullException | A specialized form of ArgumentException that you can throw when one of your arguments is null and this isn't allowed. | 
 +| ArgumentOutOfRangeException | A specialized form of ArgumentException ​that you can throw when an argument is outside the allowable range of values. | 
 +| FormatException | Throw this exception when an argument does not have valid format. | 
 +| InvalidOperationException | Throw this exception when a method is called ​that is invalid for the object'​s current state. | 
 +| NotImplementedException | This exception ​is often used in generated code where a method has not been implemented yet. | 
 +| NotSupportedException | Throw this exception when a method is invoked that you don't support. | 
 +| ObjectDisposedException | Throw when a user of your class tries to access methods when Dispose has already been called. |
  
-When this method is called, the message (and optionally the exception) are written to the Windows application event log, and the application is terminated. 
  
-//​ExceptionDispatchInfo.Throw//​ is an option for re-throwing an exception introduced in C# 5. It can be used to throw an exception and preserve the original stack trace. It can be used to throw an exception ​in one thread and catch it in another one. The .NET Framework uses this feature when dealing with //​async/​await//​. An exception that is thrown on an //async// thread is captured and re-thrown on the executing thread.+Exception types that should not be thrown ​in custom code:
  
-<code csharp>​ +^ ArithmeticException ^ A base class for other exceptions that occur during arithmetic operations. ^ 
-ExceptionDispatchInfo exceptionInfo = null; +| ArrayTypeMismatchException | Thrown when you want to store an incompatible element inside an array. | 
- +| DivideByZeroException | Thrown when you try to divide a value by zero. 
-try +| IndexOutOfRangeException | Thrown when you try to access an array with an index that is less than zero or greater than the size of the array 
-+| InvalidCastException | Thrown when you try to cast an element to an incompatible type 
-    string s = Console.ReadLine(); ​ +| NullReferenceException | Thrown when you try to reference an element that is null. |  
-    int.Parse(s); +| OutOfMemoryException | Thrown when creating a new object fails because ​the CLR doesn'​t have enough memory available 
-+| OverflowException | Thrown when an arithmetic operation overflows in checked context 
-catch (FormatException exc) +| StackOverflowException | Thrown when the execution stack is full 
-+| TypeInitializationException | Thrown when a static constructor throws an exception that is unhandled. |
-    exceptionInfo = ExceptionDispatchInfo.Capture(exc);​ +
-} +
- +
-if (exceptionInfo != null+
- +
-    // It is possible to use the ExceptionDispatchInfo.Throw method +
-    // outside of catch block.  +
-    ​exceptionInfo.Throw(); +
-+
-</​code>​+
  
  
-====References====+====Links====
  
   * MSDN: [[https://​msdn.microsoft.com/​en-us/​library/​5b2yeyab.aspx|Handling and Throwing Exceptions]]   * MSDN: [[https://​msdn.microsoft.com/​en-us/​library/​5b2yeyab.aspx|Handling and Throwing Exceptions]]
   * MSDN: [[https://​msdn.microsoft.com/​en-us/​library/​seyhszts.aspx|Best Practices for Exceptions]]   * MSDN: [[https://​msdn.microsoft.com/​en-us/​library/​seyhszts.aspx|Best Practices for Exceptions]]
  
notes/csharp/exceptions.1468862530.txt.gz · Last modified: 2016/07/18 by admin