Search code examples
c#.netclr

Are there any functions that should not throw exceptions?


When programming in C# .Net are there any functions where it is almost always a "bad idea" to throw an exception?

In C++ it is rarely a good idea to throw an exception from a destructor as it can often cause the program to terminate. Are there similar situations in C# .Net? I'm not interested in situations where exceptions are just considered bad style. I'm looking for places where throwing an exception will often lead to serious problems.


Solution

  • This is covered by Microsoft's Design Rule CA1065 (Do not raise exceptions in unexpected locations), which states:

    Methods that are not expected to throw exceptions can be categorized as follows:

    • Property Get Methods
    • Event Accessor Methods
    • Equals Methods
    • GetHashCode Methods
    • ToString Methods
    • Static Constructors
    • Finalizers
    • Dispose Methods
    • Equality Operators
    • Implicit Cast Operators