97 lines
1.9 KiB
Python
Executable File
97 lines
1.9 KiB
Python
Executable File
"""
|
|
Errores y Excepciones
|
|
"""
|
|
"""Error de sintaxis"""
|
|
# a = 5 print(a)
|
|
# SyntaxError: invalid syntax
|
|
|
|
# print('hola'))
|
|
# SyntaxError: unmatched ')'
|
|
|
|
"""Error de tipo"""
|
|
# a = 5 + 'hola'
|
|
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
|
|
|
|
"""Error de importación"""
|
|
# import supermodulo
|
|
# ModuleNotFoundError: No module named 'supermodulo'
|
|
|
|
"""Error de nombre"""
|
|
# a = b
|
|
# NameError: name 'b' is not defined
|
|
|
|
"""Error archivo no encontrado"""
|
|
# f = open('algun_archivo')
|
|
# FileNotFoundError: [Errno 2] No such file or directory: 'algun_archivo'
|
|
|
|
"""Error de valor"""
|
|
# a = [1,2,3]
|
|
# a.remove(4)
|
|
# ValueError: list.remove(x): x not in list
|
|
|
|
"""Error de indice"""
|
|
# a = [1,2,3]
|
|
# a[3]
|
|
# IndexError: list index out of range
|
|
|
|
"""Error de llave"""
|
|
# mi_dicc = {'nombre': 'Alexanderson'}
|
|
# mi_dicc['edad']
|
|
# KeyError: 'edad'
|
|
|
|
"""Levantar una excepción"""
|
|
# x = -5
|
|
# if x < 0:
|
|
# raise Exception('x debe ser positivo')
|
|
# Exception: x debe ser positivo
|
|
|
|
"""Assert, 'asegura'"""
|
|
# x = -5
|
|
# assert(x > 0), 'x no es positivo'
|
|
# AssertionError: x no es positivo
|
|
|
|
"""
|
|
Manejo de excepciones
|
|
"""
|
|
try:
|
|
a = 5/0
|
|
except Exception as e:
|
|
print('ha ocurrido un error -->', e)
|
|
|
|
try:
|
|
a = 5/0
|
|
b = a + 'que'
|
|
except ZeroDivisionError as e:
|
|
print(e)
|
|
except TypeError as e:
|
|
print(e)
|
|
else:
|
|
print('todo esta bien')
|
|
finally:
|
|
print('siempre se llega aquí')
|
|
|
|
"""
|
|
Definir excepciones propias, con clases de error propias.
|
|
(SubClase de BaseException)
|
|
"""
|
|
class ValorMuyAltoError(Exception):
|
|
pass
|
|
|
|
class ValorMuyBajoError(Exception):
|
|
def __init__(self, message, value):
|
|
self.message = message
|
|
self.value = value
|
|
|
|
def test_valor(x):
|
|
if x > 100:
|
|
raise ValorMuyAltoError('El valor es muy alto')
|
|
if x < 5:
|
|
raise ValorMuyBajoError('El valor es muy bajo', x)
|
|
|
|
try:
|
|
test_valor(2)
|
|
except ValorMuyAltoError as e:
|
|
print(e)
|
|
except ValorMuyBajoError as e:
|
|
print(e.message, e.value)
|