Python tenta…exceto…finalmente

Resumo : neste tutorial, você aprenderá sobre a try...except...finallyinstrução Python.

Introdução à instrução Python try…catch…finalmente

A try...exceptinstrução permite capturar uma ou mais exceções na trycláusula e tratar cada uma delas nas exceptcláusulas.

A try...exceptinstruçã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 upLinguagem de código:  PHP  ( php )

A finallycláusula sempre é executada independentemente de ocorrer uma exceção ou não. E é executado após a trycláusula e qualquer exceptcláusula.

O fluxograma a seguir ilustra a try...catch...finallycláusula:

Python try catch finalmente instrução

Exemplos de instruções Python try…catch…finalmente

O exemplo a seguir usa a try...catch...finallyinstruçã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 trycláusula causa uma ZeroDivisionErrorexceção excepte finallya cláusula é executada.

A trycláusula no exemplo a seguir não causa erro. Portanto, todas as instruções nas cláusulas trye finallyexecutam:

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 catchcláusula na try...catch...finallydeclaraçã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...finallya instrução Python para executar um bloco de código, independentemente de ocorrer uma exceção ou não.
  • Use a finallycláusula para limpar os recursos, como fechar arquivos.

Deixe um comentário

O seu endereço de email não será publicado. Campos obrigatórios marcados com *