Resumo : neste tutorial, você aprenderá sobre a try...except...finally
instrução Python.
Introdução à instrução Python try…catch…finalmente
A try...except
instrução permite capturar uma ou mais exceções na try
cláusula e tratar cada uma delas nas except
cláusulas.
A try...except
instrução também possui uma cláusula opcional chamada finally
:
try:
# code that may cause exceptions
except:
# code that handle exceptions
finally:
# code that clean up
Linguagem de código: PHP ( php )
A finally
cláusula sempre é executada independentemente de ocorrer uma exceção ou não. E é executado após a try
cláusula e qualquer except
cláusula.
O fluxograma a seguir ilustra a try...catch...finally
cláusula:
Exemplos de instruções Python try…catch…finalmente
O exemplo a seguir usa a try...catch...finally
instrução:
a = 10
b = 0
try:
c = a / b
print(c)
except ZeroDivisionError as error:
print(error)
finally:
print('Finishing up.')
Linguagem de código: PHP ( php )
Saída:
division by zero
Finishing up.
Neste exemplo, a try
cláusula causa uma ZeroDivisionError
exceção except
e finally
a cláusula é executada.
A try
cláusula no exemplo a seguir não causa erro. Portanto, todas as instruções nas cláusulas try
e finally
executam:
a = 10
b = 2
try:
c = a / b
print(c)
except ZeroDivisionError as error:
print(error)
finally:
print('Finishing up.')
Linguagem de código: PHP ( php )
Saída:
5.0
Finishing up.
Linguagem de código: CSS ( css )
Python try…finalmente declaração
A catch
cláusula na try...catch...finally
declaração é opcional. Então você pode escrever assim:
try:
# the code that may cause an exception
finally:
# the code that always executes
Linguagem de código: PHP ( php )
Normalmente, você usa essa instrução quando não consegue lidar com a exceção, mas deseja limpar os recursos. Por exemplo, você deseja fechar o arquivo que foi aberto.
Resumo
- Use
try...catch...finally
a instrução Python para executar um bloco de código, independentemente de ocorrer uma exceção ou não. - Use a
finally
cláusula para limpar os recursos, como fechar arquivos.