It is said that “is good to catch an exception as soon as possible”. This is the motto of the post.
You never wrote perfect code! Neither do I and probably no mortal will do this. You must accept it and try to make your code as best as possible. There are many ways to do this but today will focus the attention on the ‘default’ case.
How many times you wrote?
select variable case 1: ... case 2: ... ... case n: end
I did this a lot of times. Why do we do it? Because we assume we are bullet proof and out code is perfect. One might say that the previous snippet is not wrong but take a closer look. What if variable is not 1 and not 2 and … and not n? What happens?
In most cases unexpected things happen. Let’s assume that the select statement decides which account to use or maybe something less important like the color of a background in a game. What happens if you skip that code? Probably when you were writing the code you were not expecting any other values :) But be as paranoiac as possible: what if, somehow, in the future the value of variable will not be in the expected set.
If no case executes and you don’t expect this then the error might not be immediately visible. Maybe it will take 2 weeks until someone will complain, maybe an exception will be raise 5.000 lines from select block, you never know when and how other statements are affected.
So the solution for this is trivial. Use to default case to treat any unexpected error. The previous statement will become:
select variable case 1: ... case 2: ... ... case n: ... default: CATCH THE ERROR SOMEHOW end
The way you treat the exceptional case is up to you: abort the operation, crash the application, add a line to a log file, start the fire alarm, …
Just remember: your code is not perfect and other is even less so! Don’t expect correctness if you request it.