C# – Throw an exception in default case of a switch

cswitch statement

In my class I have a processor manager that contains a switch case. I just renamed the real name by Ant, Parrot and Snake.

        switch (name)
        {
             case "ant":
                return new AntProcessor();
             case "parrot":
                return new ParrotProcessor();
             case "snake":
                return new SnakeProcessor();
             default:
                throw new Exception($"Case {name} not found.");
        }

First, I consider than using a switch/case with a string that can take any value is not the best solution but sometime, considering time and development, this is the best dirty way to achieve his goal quickly. This is the case here:

My question is about the switch and the way I use the default case to throw an exception. Is this way to throw an exception correct? Can it be done differently?

Best Answer

The question as asked is quite meaningless. You shouldn't ask whether to throw an exception or not, you should ask how your software as a whole should react if name = "hobgoblin", for example.

So tell me: Under which circumstances could this code be executed with name = "hobgoblin"? And what should the user see happening in these circumstances? I mean you must have a plan that goes beyond "I'll throw an exception", because someone has to write code that catches the exception and handles it. Or someone will have code that catches the exception and ignores it, in which case throwing the exception isn't very useful. Or nobody catches the exception and your application crashes.

The first thing you need to do is document the behaviour of the function. Document that it will throw an exception, do nothing, assert and crash, return nil, whatever, but document it. Then implement what you documented. And then think about ways to make this safer, either by using an enum that can only have three values, or by declaring that it is legal to call this function with any string, and defining the behaviour for strings that are not handled. In that case you wouldn't throw an exception anymore.

Related Topic