Python exceto palavra- chave
Exemplo
Se a instrução gerar um erro, imprima "Algo deu errado":
try:
x > 3
except:
print("Something went wrong")
Definição e uso
A except
palavra-chave é usada em blocos try...except. Ele define um bloco de código a ser executado se o bloco try gerar um erro.
Você pode definir blocos diferentes para diferentes tipos de erro e blocos para executar se nada der errado, veja os exemplos abaixo.
Mais exemplos
Exemplo
Escreva uma mensagem se for um NameError e outra se for um TypeError:
x = "hello"
try:
x > 3
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
Exemplo
Tente executar uma instrução que gera um erro, mas nenhum dos tipos de erro definidos (neste caso, um ZeroDivisionError):
try:
x = 1/0
except NameError:
print("You have a
variable that is not defined.")
except TypeError:
print("You
are comparing values of different type")
except:
print("Something else went wrong")
Exemplo
Escreva uma mensagem se nenhum erro foi gerado:
x = 1
try:
x > 10
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
else:
print("The 'Try' code was executed without raising any errors!")
Páginas relacionadas
A palavra- try
chave.
A palavra- finally
chave.