Python excepto palabra clave
Ejemplo
Si la declaración arroja un error, imprima "Algo salió mal":
try:
x > 3
except:
print("Something went wrong")
Definición y uso
La except
palabra clave se usa en try...except blocks. Define un bloque de código para ejecutar si el bloque de prueba genera un error.
Puede definir diferentes bloques para diferentes tipos de error y bloques para ejecutar si nada salió mal, vea los ejemplos a continuación.
Más ejemplos
Ejemplo
Escriba un mensaje si es un NameError y otro si es un 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")
Ejemplo
Intente ejecutar una declaración que genere un error, pero ninguno de los tipos de error definidos (en este caso, un 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")
Ejemplo
Escriba un mensaje si no se generaron errores:
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
La try
palabra clave
La finally
palabra clave