Error in exception handling (try) in python

1

I'm doing a program that does numerical calculations, but I constantly see operations where there is division by 0 (zero) . I ended up finding a solution using if , but I still wanted to know why try can not handle this exception.

def substituicoesRetroativas(A,b):
    n = len(b)
    x = zeros(n)
    for i in range(n-1,-1,-1):
        soma = 0
        for j in range(i+1,n):
            soma += A[i,j] * x[j]
        try:
            x[i] = float(b[i] - soma)/A[i,i]
        except:
            print "Matriz Impossivel"
            break
    return np.matrix(x).transpose()

When running, I get the following error message

    Eliminacao de Gauss : 
/home/ubuntu/workspace/PASSINI/Trab 2/sS.py:23: RuntimeWarning: divide by zero encountered in double_scalars
  x[i] = float(b[i] - soma)/A[i,i]
/home/ubuntu/workspace/PASSINI/Trab 2/sS.py:20: RuntimeWarning: invalid value encountered in double_scalars
  soma += A[i,j] * x[j]
[[ nan]
 [-inf]
 [ inf]]
    
asked by anonymous 09.12.2016 / 03:40

1 answer

4

"try does not handle exception" for the simple reason that there is no exception - as you can see in the terminal, you have warnings, not exceptions.

You can change the NumPy context so that it generates exceptions instead of filling the values with Inf and NaN- see the documentation here:

link -

That is, you can do your operations within a block with with errstate set to "raise" instead of "warn" and then the try / except block will function normally.

In [3]: import numpy as np
In [4]: with np.errstate(divide='warn'):
...:     a = np.array((3,))
...:     a / 0.0
 ...:     
/home/...: RuntimeWarning: divide by zero encountered in true_divide

In [6]: b
Out[6]: array([ inf])

In [7]: with np.errstate(divide='raise'):
   ...:     a = np.array((3,))
   ...:     b = a / 0.0
   ...:     
   ...:     
---------------------------------------------------------------------------
FloatingPointError                        Traceback (most recent call last)
<ipython-input-7-2107f07a3b75> in <module>()
      1 with np.errstate(divide='raise'):
      2     a = np.array((3,))
----> 3     b = a / 0.0
    
09.12.2016 / 15:27