Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 980
erikkallen Avatar asked Jul 22 '10 22:07

erikkallen


2 Answers

What about InvalidOperationException?

like image 113
Martin Ingvar Kofoed Jensen Avatar answered Oct 24 '22 22:10

Martin Ingvar Kofoed Jensen


Why not the InvalidEnumArgumentException? It looks like it was designed specifically for this use-case.

like image 22
David Keaveny Avatar answered Oct 24 '22 22:10

David Keaveny