Intermediopython
Manejo de Errores y Excepciones
Controla errores con try/except y aprende a crear excepciones personalizadas.
try / except / finally
El bloque
try...except captura excepciones. finally se ejecuta siempre, ideal para liberar recursos.python
1def dividir(a, b):
2 try:
3 resultado = a / b
4 except ZeroDivisionError:
5 print("Error: Division entre cero")
6 return None
7 except TypeError as e:
8 print(f"Error de tipo: {e}")
9 return None
10 else:
11 return resultado
12 finally:
13 print("Operacion finalizada")
14
15dividir(10, 2)
16dividir(10, 0)Excepciones personalizadas
Crea tus propias excepciones heredando de
Exception.python
1class SaldoInsuficienteError(Exception):
2 def __init__(self, saldo, monto):
3 super().__init__(
4 f"Saldo insuficiente: tienes ${saldo:.2f}, "
5 f"intentaste retirar ${monto:.2f}"
6 )
7
8class CuentaBancaria:
9 def __init__(self, titular, saldo=0):
10 self.titular = titular
11 self.saldo = saldo
12
13 def retirar(self, monto):
14 if monto > self.saldo:
15 raise SaldoInsuficienteError(self.saldo, monto)
16 self.saldo -= monto
17
18try:
19 cuenta = CuentaBancaria("Ana", 100)
20 cuenta.retirar(150)
21except SaldoInsuficienteError as e:
22 print(e)