Which Exception Should I Throw to Signal an Internal Error in my Program?

Viewed 6968

Which exception should I use when the program reaches a logic state that I "know" won't happen, and if it does, something is terribly bad?

For example:

int SomeFunction(int arg) {
    SomeEnum x = Whatever(arg, somePrivateMember);
    switch (x) {
        case SomeEnum.Value1:
            return SomeFunction1();
        case SomeEnum.Value1:
            return SomeFunction2();
        default:
            throw new WhatTypeToThrow();
    }
}

Clearly, ArgumentException is a long-shot here since the invalid value for x could have come from a bug in Whatever(), or an invalid combination of any arguments and/or the current instance state.

I'm looking for something such as an InvalidProgramStateException, InternalErrorException or similar.

Of course I could define my own, but I wonder if there is a suitable exception in the framework.

Edit: Removed the simple sample code to reduce amount of ArgumentException answers.

7 Answers

You should consider using Code Contracts to not only throw exceptions in this case, but document what the failed assumption is, perhaps with a friendly message to the programmer. If you were lucky, the function you called (Whatever) would have a Contract.Ensures which would catch this error before you got your hands on it.

Related