When working with built-in types like int
and float
in Python, it's common to employ exception handling in cases where input might be unreliable:
def friendly_int_convert(val):
"Convert value to int or return 37 & print an alert if conversion fails"
try:
return int(val)
except ValueError:
print('Sorry, that value doesn\'t work... I chose 37 for you!')
return 37
Are there any prominent edge-cases to be aware of when using str()
?
def friendly_str_convert(val):
"Convert value to str or return 'yo!' & print an alert if conversion fails"
try:
return str(val)
except Exception: # Some specific Exception here
print('Sorry, that value doesn\'t work... I chose \'yo!\' for you!')
return 'yo!'
I really don't like using a broad Exception
since there are cases like NameError
that signify a problem with the code and should raise an error. I've considered UnicodeError
as a candidate but I'm not sure whether str()
causes it (vs. foo.encode()
and foo.decode()
where it's easier to understand) and would love an example of what input, if any, would trigger it.
In summary: Is it generally safe to use str()
without a try
/ except
block even with unreliable input?