4

I know that float("foo") could raise a ValueError, so I wrote my method as follows:

def cast_to_float(value: str) -> float:
    try:
        return float(value)
    except ValueError as e:
        # deal with it

However, I've just realized that float() can also raise an OverflowError. So I'm wondering whether there are other types of exceptions I am not catching. I understand that using except Exception is a bad practice.

How can I find all the exception types that float() can raise?

I have tried the docs as well as the “Go to Definition” menu of my IDE, but I can't find where the exceptions are raised.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
ebosi
  • 1,285
  • 5
  • 17
  • 37
  • 1
    Did you read e.g. https://stackoverflow.com/q/1591319/3001761? Note `TypeError` is a possibility too. But the question isn't what can it throw so much: what can you deal with? – jonrsharpe Apr 27 '23 at 13:23
  • Thanks @jonrsharpe, it's very relevant indeed! I did read it beforehand, but couldn't fully make sense of [that answer](https://stackoverflow.com/a/1591432/5433628). [This](https://stackoverflow.com/a/1591337/5433628) is an interesting solution to XY problem, but not what I'm looking for here. Perhaps the originality (as far as I can tell) of my question is that it's about a method of the standard library. – ebosi Apr 27 '23 at 13:30
  • It could be a duplicate of [How to list all exceptions a function could raise in Python 3?](https://stackoverflow.com/q/32560116/5433628), though. – ebosi Apr 27 '23 at 13:34

1 Answers1

2

As for the built-in functions, we need to look for them in its source code. Perhaps the easiest way is to look for CPython's unit tests, which are written in Python.

Here is the link. Search for assertRaises.

As a side note, if value is guaranteed to be str, then it seems that ValueError is the only possible error.

ken
  • 1,543
  • 1
  • 2
  • 14