TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C# Coding Standard
Search

Rule:  8@102Checked automatically with code checker

Synopsis:Do not throw exceptions from unexpected locations
Language:C#
Severity Level:1
Category:Exceptions


Description:

Throwing an exception from some locations are unexpected and can cause problems. For example when you call an exception from inside a finalizer, the CLR will stop executing the finalizer, and pass the exception to the base class finalizer (if any). If there is no base class, then the finalizer is discarded.

Do not throw exceptions from the following locations:
LocationNote
Event accessor methodsThe followings exceptions are allowed: System.InvalidOperationException, System.NotSupportedException and System.ArgumentException. This also includes their derivates.
Equals methodsAn Equals method should return true or false. Return false instead of an exception if the arguments to not match.
GetHashCode() methodsGetHashCode() should always return a value, otherwise you lose values in a hash table.
ToString methodsThis method is also used by the debugger to display information about objects in a string format. Therefore it should not raise an exception.
Static constructorsA type becomes unusable if an exception is thrown from its static constructor.
Finalizers (finalizers)Throwing an exception from a finalizer can cause a process to crash.
Dispose methodsDispose methods are often called in finally clauses as part of cleanup. Also Dispose(false) is called from a finalizer, which in itself should not throw an exception als.
Equality Operators (==, !=)Like the Equals methods, the operators should always return true or false.
Implicit cast operatorsA user is usually unaware that an implicit cast operators is called, therefore throwing an exception from them is unexpected and should not be done.
Exception constructorCalling a exception constructor is done to throw an exception. If the constructor throws an exception, then this is confusing.


Literature References:
MS Design Design Warnings