0

My understanding is that python's default warnings are not python Warnings, but printed messages. So I went ahead and used np.seterr() to try to catch them:

import numpy as np

np.seterr(all='warn')

try:
    np.array([1]) / np.array([0])
except Exception as e:
    raise Exception('exception caught in except block') from e

I'd expect the code above to catch the warning in the except block, though only the printed warning message is displayed (python 3.10.6, numpy 1.21.5).

From the documentation on np.seterr():

warn: Print a RuntimeWarning (via the Python warnings module).

Which, read carefully, does say that it only prints a warning using the Warning module rather than raising a Warning ... but I'm a bit confused as to why its built this way. What use is setting something to 'warn' if not the case above?

The behavior also seems inconsistent with this popular, related question

eretmochelys
  • 543
  • 1
  • 5
  • 15
  • _"I'd expect the code above to catch the warning in the except block"_ Warnings aren't exceptions and are [caught differently](https://stackoverflow.com/q/5644836/11082165). _"The behavior also seems inconsistent"_ In that answer, the author promoted warnings to exceptions with `warnings.filterwarnings("error")` – Brian61354270 Jul 27 '23 at 19:19
  • that does answer my question, thank you! I had checked if `Warning` was a subclass of `Exception` (it is) and assumed they were handled similarly. – eretmochelys Jul 27 '23 at 19:41
  • Glad it was helpful! Cheers – Brian61354270 Jul 27 '23 at 19:59

0 Answers0