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.
Well, your code can be perfect if you take care of variable initialization.
For example, if you do a
color = 0×0;
switch (colid) {
case WHITE: color = 0xFFFFFF;
case BLUE: color = 0xFF0000;
etc.
}
Nobody will punish you.
Rule of thumb: switch goes very well with enums. :) And the compiler will notify you that you forgot a case or more (gcc does, at least, and any decent compiler should).
Dorin, in that case you need to check the variable after you finish with the switch. Switch goes very well with enums – that is true but if the memory gets corrupted and you have some garbage there?
Well, garbage is garbage anyway – if the memory gets corrupted, then you have a different problem, do you?:)