This is probably a basic question, better explained through code:
public void checkStatus {
int status = UNKNOWN;
if (somecondition) {
status = STATUS_UP;
} elseif (someothercondition) {
status = STATUS_DOWN;
}
}
So the problem is, by definition I do not know all the possible conditions that might affect the STATUS, and I didn’t want the compiler to throw ‘my not be defined’ error by not initializing the status local variable.
Bottom line my app won’t work with a status set to UNKNOWN, I’ve just set it to shut up the compiler.
Question: how can I approach this elegantly, I’ve considered throwing an fatal exception at the end of the method should the status still be set to UNKNOWN, but that feels a bit ‘ugly’.
Thank you.
I always put a
throwat the end of theif / then / elsechain, and do not assign the default value to the variable upfront. If the exception is thrown, it tells me not only that the application cannot continue, but also reports the reason why it cannot proceed. Moreover, it does that as soon as it finds out that it cannot proceed, which is very desirable for error reporting (generally, you want to report an error as soon as possible).There is one special case, when you structured your code in such a way that the combination of
someconditions is such that you never run off the tail of theif / then / elsechain, but the compiler cannot verify it automatically. For example, you validated the input before, and you know that there is no path through your code that can change it. In this specific case you should use an assertion rather than throwing an exception, because it indicates an error with your reasoning about your code, rather than a simple coding error.