Home > other >  Breakpoint when encountering RunTimeWarning
Breakpoint when encountering RunTimeWarning

Time:06-01

I am having trouble getting the following code to work in Python:

for t in range(-5,5):
    try:
        a = np.log(t)
    except RunTimeWarning:
        breakpoint()

What I want is to execute the breakpoint statement, when the log function is evaluated from -5 to 0.

CodePudding user response:

When using np.log(0), numpy won't throw an exception but a warning. These are significantly different from exceptions as an exception will stop the current code from running, whereas a warning just notifies you but keeps the code running.

Take this example:

>>> x = np.log(0)

Warning (from warnings module):
  File "<pyshell#1>", line 1
RuntimeWarning: divide by zero encountered in log
>>> x
-inf

As you can see the variable x does get a value assigned -> the warning never kept log(...) from running and returning a value.

So to solve your problem, you'd have to check if the value passed to your code is 0 before calling np.log. Or if you don't want -inf to be a valid return value but still need to call np.log for some reason, you can check if the value is -inf after the call. However it's best practise not to write code that causes warnings so you should probably just check if it's 0 before calling log.

You can read more about warnings in the python docs.

  • Related