How to capture all exceptions in Python?

Asked

Viewed 2,086 times

4

How to capture any and all Python exceptions? Are there any keywords for this?

Like in Java you just make one

try {
}
catch(Exception ex) {
}

2 answers

6


It’s the same thing. Just use one try-except.

try:
    aluma_coisa()
except Exception as e:
    fazer_algo(e)
  • to see the exception you can use print(str(e))

  • So Python, does it have a hierarchy similar to Java? I will study better.

  • 2

    This @Wilker. Except that the most generic Exception of Python is the BaseException. But it captures errors like KeyboardInterrup and SystemExit and usually you don’t want that.

4

I will try to add something to @jbueno’s reply, as there are some more details in the Python exceptions survey. I am only going to present here what I consider most important, explaining, mainly, with examples. Full explanation can be seen in the documentation, at that link.

Exception is the base class for all exceptions, if Voce has doubts that the code may raise an exception, use the Try-except block

try:
    f = open('file','w')
    f.write('testing Exception handling')
except IOError:
    print ("Erro, arquivo não encontrado ou erro nos dados")
else:
    print ('Sucesso na escrita do arquivo')

Clausula Except

No exceptions
Note that Voce can use the except clause without explicitly stating the exception, with this Voce will consider all exceptions, but this is not considered a good programming practice, because the developer can not identify the "root" of the problem, in python always try to follow one of the statements of PEP 20 "Explicit is better than implicit".

Multiple exceptions
The clause except also accepts multiple exceptions.

try:
  # implementação
except (KeyError, IndexError)
  # Se houver qualque exception, execute esse bloco
...

Clause Try-Finally

You can use Finally together with Try when Voce wants a block to run anyway, with or without exception.

try:
    f = open('file','w')
    f.write('testing Exception handling')
finally:
    # Esse bloco vai ser execudo de qualquer forma

Additional examples

With Try-Finally-except.

try:
    f = open('file','w')
    try:
        f.write('testing Exception handling')
    finally:
        print ('Ok, fechando o arquivo')
        f.close()
except IOError:
    print "Erro arquivo ausente ou corrompido"     

An example combining exceptions.

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("Erro de sistema operacional: {0}".format(err))
except ValueError:
    print("Impossível converter dados do arquivo em um inteiro.")
except:
    print("Erro inesperado:", sys.exc_info()[0])
    raise

In this example, the exception information is presented.

def multply(x,y):
    try:
       r = (x*y)
    except Exception as e:
       print('Erro :')
       print ('Tipo: ', type(e))
       print ('Argumentos: ', e.args)
       print (e)
    else:
        return r

>>> multply('a','b')
Erro :
Tipo:  <class 'TypeError'>
Argumentos:  ("can't multiply sequence by non-int of type 'str'",)
can't multiply sequence by non-int of type 'str'

Easter Egg

Open the python console and type:

>>> import this

Reference
Errors and Exceptions.
PEP 20, Python’s Zen.

Browser other questions tagged

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