None Exception rasied in try except block
Question:
I use a simple function:
def is_float(value):
try:
float(value) #float(value if value else "")
return True
except ValueError:
return False
to check if an value is float or not.
Now, even though the check is in an try except block, this error is raised if the value is None:
2023-02-06 09:47:27,021 app - ERROR:Exception ....
TypeError: float() argument must be a string or a number, not 'NoneType'.
Can someone explain why?
If you want to try it yourself, just execute the function with a None value and it will throw.
Answers:
Option #1: Use Exception
clause (broadest) instead to handle the None
type.
def is_float(value):
try:
float(value)
return True
except Exception:
return False
Option #2: except
the errors that you expect.
def is_float(value):
try:
float(value)
return True
except (TypeError, ValueError):
return False
Tests:
assert is_float(1.2)
assert is_float(3)
assert is_float(0)
assert not is_float(None)
Ah okay, nvm, I just saw my mistake.
except Exception as e:
would be what I wanted.
That was silly.
I use a simple function:
def is_float(value):
try:
float(value) #float(value if value else "")
return True
except ValueError:
return False
to check if an value is float or not.
Now, even though the check is in an try except block, this error is raised if the value is None:
2023-02-06 09:47:27,021 app - ERROR:Exception ....
TypeError: float() argument must be a string or a number, not 'NoneType'.
Can someone explain why?
If you want to try it yourself, just execute the function with a None value and it will throw.
Option #1: Use Exception
clause (broadest) instead to handle the None
type.
def is_float(value):
try:
float(value)
return True
except Exception:
return False
Option #2: except
the errors that you expect.
def is_float(value):
try:
float(value)
return True
except (TypeError, ValueError):
return False
Tests:
assert is_float(1.2)
assert is_float(3)
assert is_float(0)
assert not is_float(None)
Ah okay, nvm, I just saw my mistake.
except Exception as e:
would be what I wanted.
That was silly.