try-except and RuntimeWarning

Viewed 1672

This should be an easy one, but it's cracking my head.

A statement in one of my Python scripts is giving a RuntimeWarning message:

RuntimeWarning: invalid value encountered in double_scalars
  z = 1.0/(D*ppr + E*y**2 - F*y**G)

Still the script runs, plots a beautiful chart, shows acceptable results, etc. But this warning is bugging me. It indicates that something in my script is fishy.

I wanted to check values whenever this happens. Shouldn't this work?

  try:
    z = 1.0/(D*ppr + E*y**2 - F*y**G)
  except RuntimeWarning:
    print (D, E, F, G, ppr, y)

But it doesn't (the script runs as before, though). 'except Warning:' doesn't work either.

Yet those two exceptions are listed here: https://docs.python.org/3/library/exceptions.html

What's the problem here? Thanks for any help.

PS: I'm using Spyder 4.1.1 IDE. Does that make any difference?

1 Answers

According to the documentation on the warnings module, this is how you "catch" warnings:

with warnings.catch_warnings(record=True) as w:
    z = 1.0/(D*ppr + E*y**2 - F*y**G)
    if len(w) > 0:
        print (D, E, F, G, ppr, y)

Disclaimer: Note that it is probably not in your best interest to ignore those warnings, but to understand why they happen and fix the code, then remove the warning check.

Related