Can anyone tell me what the try:
and except
means?
I need to do a program and I have a question about this.
Can anyone tell me what the try:
and except
means?
I need to do a program and I have a question about this.
try/except
is for exception handling.
Exception is when something does not happen the way it was planned. It can be said that programs have a normal flow, and an exceptional flow which are the exceptions.
The syntax is
try:
código a tentar
except AlgumaExcecao:
código a executar no caso da exceção
else:
código a executar caso não ocorra exceção em try
finally:
código que é executado sempre, independente de haver uma exceção em andamento ou não
The python functions already raise exceptions automatically when something happens, for example if you try to open a file and it does not exist:
try:
f = open('arquivo')
except OSError:
print('Nao deu pra abrir o arquivo')
else:
print('Arquivo aberto!')
You can even raise exceptions in your code, to notify the user of their functions of some exceptional behavior
class DeuProblema(Exception): pass
def faz_alguma_coisa():
...
if ...:
raise DeuProblema()
...
Hence who is using:
try:
faz_alguma_coisa()
except DeuProblema:
tenta_outra_coisa()
Another very common use is to make sure that a certain code will run:
d = abre_banco_de_dados() # precisa ser fechado
try:
...
finally:
d.close() # garante que o banco será fechado mesmo em caso de erro
Finally, an important tip. Do not use except
pure this way:
try:
...
except: # pega qualquer exceção (EVITE!)
...
This type of construction hides any and all errors making it very difficult to develop the program because the errors will be silenced. You can also catch exceptions you do not want to catch, such as KeyboardInterrupt
or MemoryError
. Instead, always pass the exception you want to catch, or use Exception
to catch most exceptions.
try:
...
except ValueError: # pega somente ValueError
...
except Exception: # não pega MemoryError, SystemExit, KeyboardInterrupt
log.exception()
raise # sempre suba novamente a exceção não tratada,
# para que seja visível
The idea of try except is to test critical points of the code, ie places where there is a great possibility of errors.
They are widely used in reading files or user input data. For example, you want the user to type an integer to perform a math operation, if he types a string, the operation will not work.
def div(a,b):
try:
x = a/b
return x
except:
return "Nao foi possivel realizar a operacao"
When calling the function this way, the return will be an integer value (in this case, 4)
div(20,5)
When calling
div('a','b')
The return will be the message Could not perform the operation
Hello, with a very simple explanation:
try:
print("Tudo ocorreu sem nenhum erro, como esperado!")
except:
print("Não foi possível executar a função tal, erro tal.")
As you can see in the example above, your code will be placed inside try
, but if there is no success in execution it will be directed to except
immediately and will be executed whatever you put inside except
.
Without this control python will display an error, but with it, you will be executing whatever you want.