I’ve googled for quiet a time now and I still don’t know which exception to use in which scenario. I’ve read that it’s bad practice to raise SystemExceptions in your own code, because those exception should better get raised by the CLR.
But well, now I want to know what Exeption I should raise in different scenarios. Let’s say I have a method which gets invoked with an enum as Parameter. That isn’t a very good example – it just came off the top of my head.
public enum CommandAppearance
{
Button,
Menu,
NotSpecified
}
//...
public void PlaceButtons(CommandAppearance commandAppearance)
{
switch(commandAppearance)
{
case CommandAppearance.Button:
// do the placing
case CommandAppearance.Menu:
// do the placing
case CommandAppearance.NotSpecified:
throw ArgumentOutOfRangeException("The button must have a defined appearance!")
}
}
What would it be here? Is there some kind of site, where I can get an overview? Are there any patterns which tell you what kind of exception to raise? I’d just need some tips at this topic, because I’m pretty unconfident with this.
I think raising just new Exception()s isn’t good practice, either, is it?
For your example scenario, I would suggest either:
ArgumentOutOfRangeExceptionif the method supports ALL values in the enum and an invalid value is passed.NotSupportedExceptionif the method supports a subset of the values in the enum.Generally speaking, you want to make use of the exception types See this list of exceptions in the .net framework where possible and it makes sense, otherwise you want to introduce your own. This may involve adding a common application exception for your application and adding more specific ones which inherit from it.
e.g.