How to catch any exception in Python? Is there a keyword for this?
As in Java, just do one
try {
}
catch(Exception ex) {
}
How to catch any exception in Python? Is there a keyword for this?
As in Java, just do one
try {
}
catch(Exception ex) {
}
try-except
.
try:
aluma_coisa()
except Exception as e:
fazer_algo(e)
I'll try to add something to @jbueno's answer, as there are a few more details in Python exception picking. I will only present here what I consider most important, elucidating, mainly, with examples. Full explanation can be seen in the documentation, in this link .
Exception is the base class for all exceptions, if you have any doubt that the code might 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')
Clause Except
No exceptions
Note that you can use the except clause without explicitly specifying the exception, so you 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 follow one of the PEP 20 statements "Explicit is better than implicit."
Multiple exceptions
The except clause also accepts multiple exceptions.
try:
# implementação
except (KeyError, IndexError)
# Se houver qualque exception, execute esse bloco
...
Try-finally clause
You can finally use together with try when you want a block to be executed anyway, with an exception occurring or not.
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 displayed.
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, The Zen of Python.