I have the following code in a shared component:
public class MyClass {
public void DoWork() {
// ...
if (someConditionWhichShouldAlwaysBeFalse) {
throw new Exception("If we get here, there must be a bug in MyClass.");
}
}
}
I'm wondering if there's an appropriate built-in exception type in .NET that indicates:
MyClass
perfectly legally, and the error is entirely caused by bugs within MyClass
In a way, I just want a stronger, exception-based version of Debug.Assert()
. The purpose is entirely to catch bugs within my code and I expect callers not to catch the exception (except maybe for logging and rethrow).
Is there a built-in type in the framework that suits this purpose? I've seen people use InvalidOperationException
sometimes but my understanding is that IOE should be used for caller input which is inconsistent with object state (i.e. it is still fundamentally a caller error).
Sounds to me like UnreachableException is what you're looking for, introduced in .NET 7:
The exception that is thrown when the program executes an instruction that was thought to be unreachable