Description
Normally, the finally
keyword is used with try
-catch
constructions and the code therein will run regardless of whether the try
code throws or not.
There have been a number of times I've wanted something similar for if
constructions. For example (just an example!!!), when parsing a numeral string into a custom numeric type, you might want to check the sign, and if the sign is found, increment the parse index or alternatively shorten the string being parsed to not contain the sign:
if (myString.startsWith("+")) {
parsedNum.setSign(1);
} else if (myString.startsWith("-")) {
parsedNum.setSign(-1);
} finally {
myString = myString.substring(1);
}
Without finally
, you have to do one of the following things:
- Duplicate code (if the code is long, this can be remedied by extracting it into a function of course):
if (myString.startsWith("+")) {
parsedNum.setSign(1);
myString = myString.substring(1);
} else if (myString.startsWith("-")) {
parsedNum.setSign(-1);
myString = myString.substring(1);
}
- Indicator variable:
bool hasSign = false;
if (myString.startsWith("+")) {
parsedNum.setSign(1);
hasSign = true;
} else if (myString.startsWith("-")) {
parsedNum.setSign(-1);
hasSign = true;
}
if (hasSign) {
myString = myString.substring(1);
}
- Duplicate condition:
if (myString.startsWith("+") || myString.startsWith("-")) {
if (myString.startsWith("+")) {
parsedNum.setSign(1);
} else if (myString.startsWith("-")) {
parsedNum.setSign(-1);
}
myString = myString.substring(1);
}
These alternatives are fine, but I think it would be more concisely expressed with finally
, and be less prone to error.
The exact meaning of finally
here would be: execute this code if any branches of the condition are taken; do not execute it if no branches of the condition are taken.