简体   繁体   中英

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.

  1. A static constructor or a type constructor. If there is an unhandled exception the type will not be loaded into the application domain and will return the last Exception every time you try to call it.
  2. in the finalizer

In addition to the other places mentioned, I would add async void methods, particularly after the first await . The problem here is that if the await requires rescheduling then any exception that bubbles out of the method may land in unexpected locations. eg. if you await using .ConfigureAwait(false) or if the async void method is called from a background thread, then the exception would land in the thread-pool with a direct path to becoming unhandled.

Having said that, there are only a few places where I think it's reasonable to use async void and if an exception bubbles out of them then you have probably left it too late to handle the exception correctly anyway.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM