Excepciones

Programación orientada a objetos en Python

Alex Yarosh

Content Quality Analyst @ DataCamp

a = 1
a / 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    1/0
ZeroDivisionError: division by zero
a = [1,2,3]
a[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    a[5]
IndexError: list index out of range
a = 1
a + "Hello"
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    a + "Hello"
TypeError: unsupported operand type(s) for +: /
'int' and 'str'
a = 1
a + b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    a + b
NameError: name 'b' is not defined
Programación orientada a objetos en Python

Manejo de excepciones

  • Evitar que el programa termine cuando se lanza una excepción
  • try - except - finally:
try:
  # Intenta ejecutar algún código

except ExceptionNameHere: # Ejecuta este código si ocurre ExceptionNameHere
except AnotherExceptionHere: #<-- múltiples bloques except # Ejecuta este código si ocurre AnotherExceptionHere ...
finally: #<-- opcional # Ejecuta este código pase lo que pase
Programación orientada a objetos en Python

Lanzando excepciones

  • raise ExceptionNameHere('Mensaje de error aquí')
def make_list_of_ones(length):
    if length <= 0:
       raise ValueError("¡Longitud inválida!")  # <--- Detendrá el programa y lanzará un error
    return [1]*length   
make_list_of_ones(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    make_list_of_ones(-1)
  File "<stdin>", line 3, in make_list_of_ones
    raise ValueError("¡Longitud inválida!")
ValueError: ¡Longitud inválida!
Programación orientada a objetos en Python

Las excepciones son clases

  • las excepciones estándar heredan de BaseException o Exception
    BaseException
    +-- Exception
        +-- ArithmeticError                     # <--- 
        |    +-- FloatingPointError
        |    +-- OverflowError
        |    +-- ZeroDivisionError              # <---
        +-- TypeError
        +-- ValueError
        |    +-- UnicodeError
        |         +-- UnicodeDecodeError
        |         +-- UnicodeEncodeError
        |         +-- UnicodeTranslateError
        +-- RuntimeError
       ...
    +-- SystemExit
    ...
    
1 https://docs.python.org/3/library/exceptions.html
Programación orientada a objetos en Python

Excepciones personalizadas

  • Heredar de Exception o una de sus subclases
  • Usualmente una clase vacía
class BalanceError(Exception): pass
class Customer:
   def __init__(self, name, balance):
    if balance < 0 :
       raise BalanceError("¡El saldo debe ser no negativo!")
    else:
       self.name, self.balance = name, balance

Programación orientada a objetos en Python
cust = Customer("Larry Torres", -100)
Traceback (most recent call last):
  File "script.py", line 11, in <module>
    cust = Customer("Larry Torres", -100)
  File "script.py", line 6, in __init__
    raise BalanceError("¡El saldo debe ser no negativo!")
BalanceError: ¡El saldo debe ser no negativo!
  • La excepción interrumpió el constructor → objeto no creado
cust
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    cust
NameError: name 'cust' is not defined
Programación orientada a objetos en Python

Capturando excepciones personalizadas

try:
  cust = Customer("Larry Torres", -100)
except BalanceError:
  cust = Customer("Larry Torres", 0)
Programación orientada a objetos en Python

¡Vamos a practicar!

Programación orientada a objetos en Python

Preparing Video For Download...