Exception handling (Try) error in python

Asked

Viewed 513 times

1

I am making a program that makes numerical calculations, but constantly appear to me operations where there is division by 0 (zero). I ended up finding a solution using if, but still wanted to know why the try can’t handle that 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 executing 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]]
  • 1

    you would have an example of parameters for the function?

  • 1

    you are using some library in this code?

  • @Jeandersonbarroscândido I am using the numpy.

1 answer

4


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

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

https://docs.scipy.org/doc/numpy/reference/generated/numpy.errstate.html -

That is, you can do your operations within a block with with the errstate set to "raise" instead of "warn" and then the Try/except block will work 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.