Coming from a Java background I'm currently learning Python and I found this example in a Python beginner book. It's proposing the use of the ValueError
exception in a function for a spreadsheet-like calculation to return 0
for empty cells like this:
def cell_value(string):
try:
return float(string)
except ValueError:
if string == "":
return 0
else:
return None
Now, to my understanding, in the Java world, such a use of exceptions would be frowned upon, because having an empty cell in a spreadsheet and interpreting it as 0
is clearly not an exceptional condition but rather normal program flow and in Java "exceptions are, as their name implies, to be used only for exceptional conditions; they should never be used for ordinary control flow." (Joshua Bloch: Effective Java)
I already read another similar question and answer suggesting that this rule might not be adhered to as strictly in the Python world, but I'm still not sure about the given example.
Would the use of ValueError
as illustrated in the function above be considered bad practice in Python or not?