Exceptions · Exceções
When things go wrong
- A runtime error normally crashes the program.
- An exception is Python's signal that something went wrong.
- Exception handling lets you catch it and keep running.
Quando algo dá errado
- Um erro de tempo de execução normalmente crasha o programa.
- Uma exceção é o sinal do Python de que algo deu errado.
- O tratamento de exceções permite capturá-la e continuar executando.
try / except
- Put risky code in a
try:block. - If it raises an exception, the
except:block runs instead of crashing. - If nothing goes wrong, the
exceptblock is skipped.
try / except
- Coloque código arriscado em um bloco
try:. - Se ele gerar uma exceção, o bloco
except:executa em vez de crashing. - Se nada der errado, o bloco
excepté pulado.
try:
number = int("not a number")
except ValueError:
number = 0
print(number)
Catch the right error
- Name the type of error you expect:
except ValueError:. ValueErroris bad text for a number;ZeroDivisionErroris divide by zero.- Catching a specific type means you do not hide other bugs.
Capturar o erro certo
- Nomeie o tipo de erro que você espera:
except ValueError:. ValueErroré texto inválido para um número;ZeroDivisionErroré divisão por zero.- Capturar um tipo específico significa que você não esconde outros bugs.
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
finally and raise
- A
finally:block always runs, error or not — good for cleanup. raiselets you signal an error on purpose.raise ValueError("message")stops the code unless something catches it.
finally e raise
- Um bloco
finally:sempre executa, com ou sem erro — bom para limpeza. raisepermite que você sinalize um erro propositalmente.raise ValueError("message")interrompe o código a menos que algo o capture.
try:
raise ValueError("bad value")
except ValueError as e:
print("Caught:", e)
finally:
print("Always runs")
Why it matters
- A robust program should not crash on bad input.
- Handling exceptions lets it warn the user and carry on.
- It also makes sure files and other resources are closed cleanly.
Por que importa
- Um programa robusto não deve crashing com entrada errada.
- Tratar exceções permite avisar o usuário e continuar.
- Também garante que arquivos e outros recursos sejam fechados limpidamente.
Common mistakes
- Catch a specific error (
except ValueError:), not a bareexcept:. - Put only the risky line inside the
try.
Erros comuns
- Capture um erro específico (
except ValueError:), não umexcept:nu. - Coloque apenas a linha arriscada dentro do
try.
Now you try
- Use
try/except(andraisein the last task). - Press Check answer to test your code.
Agora você tenta
- Use
try/except(eraisena última tarefa). - Clique em Check answer para testar seu código.
try / except
Code runs in try; if it fails, control jumps to except. · O código roda em try; se falhar, o controle salta para except.
Write safe_int(text) that returns · decrescentes int(text). If the text is not a valid number, catch the ValueError and return -1 instead. · Escreva safe_int(text) que retorna int(text). Se o texto não for um número válido, capture a ValueError e retorne -1 em vez disso.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write divide(a, b) that returns · decrescentes a / b. If b is 0, catch the ZeroDivisionError and return None instead. · Escreva divide(a, b) que retorna a / b. Se b for 0, capture a ZeroDivisionError e retorne None em vez disso.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write withdraw(balance, amount). If amount is more than balance, raise ValueError. Otherwise return · retorno the new balance (balance - amount). · Escreva withdraw(balance, amount). Se amount for maior que balance, raise ValueError. Caso contrário return · retorno o novo saldo (balance - amount).
Click Run to see the output here. · Clique em Executar para ver a saída aqui.