try and except

Trate um erro em vez de travar. O código em try é executado; se ele gerar o erro indicado, except é executado.

Sintaxe

try:
...
except ValueError:
...
  • Nomeie o erro que você espera. Um except sem tipo esconde bugs reais.

Exemplo

try:
    int("abc")
except ValueError:
    print("not a number")

Saída:

not a number

Erros comuns

  • Capturar tudo com except: torna os bugs invisíveis.
  • Mantenha o bloco try pequeno, para saber qual linha falhou.

Pratique