0

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.

andypea
  • 1,343
  • 11
  • 22
  • It's just a policy. I worked in one location where the rule was to always throw it. – JWP Feb 10 '21 at 23:05
  • https://stackoverflow.com/questions/2692004/c-sharp-finalizer-throwing-exception – Stanislav Feb 10 '21 at 23:16
  • Thanks for the link. It's really helpful! – andypea Feb 10 '21 at 23:33
  • It is quite a different ordeal in C++, std::terminate() does not leave anybody a decent guess why the program terminated. C# does not have that problem, you can (almost) always get a good stack trace. The (almost) clause provided this website with its name. Only thing to worry about is the program actually trying to catch an exception. Don't throw from code running in a *finally* block, it replaces an active exception. – Hans Passant Feb 10 '21 at 23:44

3 Answers3

2
  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
Stanislav
  • 459
  • 3
  • 6
1

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.

Brian Reichle
  • 2,798
  • 2
  • 30
  • 34
0

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
andypea
  • 1,343
  • 11
  • 22