3

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?

Carlos Gouveia
  • 247
  • 2
  • 8
  • this depend on your code and the instance the script using, better/proper wayis to log the result and see the values there – sahasrara62 Apr 05 '20 at 03:36
  • 5
    Warnings are not exceptions and therefore can't be caught like that. See the `warnings` module [documentation](https://docs.python.org/3/library/warnings.html) for details on warnings management. – Klaus D. Apr 05 '20 at 03:37
  • 2
    Does this answer your question? [In Python, how does one catch warnings as if they were exceptions?](https://stackoverflow.com/questions/5644836/in-python-how-does-one-catch-warnings-as-if-they-were-exceptions) – dspencer Apr 05 '20 at 03:38
  • 2
    Warnings *are* exceptions, but they usually aren't raised as exceptions. They can only be caught with `except` if they're actually raised as exceptions. – user2357112 Apr 05 '20 at 03:40
  • @dspencer, that was very useful indeed. Case closed, many thanks! – Carlos Gouveia Apr 05 '20 at 03:44

1 Answers1

2

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.