Search code examples
c#.netexception

Is there any built-in exception type for a boneheaded exception in .NET?


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:

  1. This exception is boneheaded, i.e. it must indicate a bug in my code
  2. It is not caused by any illegal caller input. The caller is using 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).


Solution

  • 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