3

Code

s = np.zeros(2)
try:
    a = s[0]/s[1]
except:
    a = 10.0
print(a)

raises warning as mentioned in the title of the question and prints nan. It's rather strange, isn't it? How can it be explained and corrected?

Prune
  • 76,765
  • 14
  • 60
  • 81
Vladimir
  • 151
  • 1
  • 10

1 Answers1

2

It appears that you expect a divide-by-zero exception. The run-time system doesn't work this way: you get a warning and a result of nan. Thus, your exception block doesn't get tripped. Instead, try this:

if s[1]:
    a = s[0] / s[1]
else:
    a = 10.0
Prune
  • 76,765
  • 14
  • 60
  • 81
  • If you want to trap warnings as well as exceptions, see [here](https://stackoverflow.com/questions/5644836/in-python-how-does-one-catch-warnings-as-if-they-were-exceptions#30368735). – Prune Apr 04 '18 at 17:40
  • Thanks a lot for your answer, it is quite clear. But what I don't understand is why the code does not raise an exception? – Vladimir Apr 04 '18 at 17:46
  • Other words for what purpose it was done that way - just warning, not exception? – Vladimir Apr 04 '18 at 17:47
  • To answer "what purpose", you'll need to read through the language design postings; I expect that there is at least one explanation in the PEP documents. – Prune Apr 04 '18 at 17:50
  • The application I have locally is that we want to work with large AI data sets with some missing values. It's very convenient to have `nan` semantics that inherently support that concept, rather than having to write custom software to properly fill in `nan` and skip or impute said values. – Prune Apr 04 '18 at 17:51
  • But from my point of view it's not the question of python as language - it's concerning only numpy, isn't it? – Vladimir Apr 04 '18 at 18:00
  • Ah -- right. It's just numpy. PEP references are useless. – Prune Apr 04 '18 at 18:02