Exceções

Introdução à programação orientada a objetos em Python

George Boorman

Curriculum Manager, 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
Introdução à programação orientada a objetos em Python

Tratamento de exceções

  • Evite que o programa termine quando uma exceção ocorrer
  • try - except - finally:
try:
    print(5 + "a")

except TypeError: print("You can't add an integer to a string, but you can multiply them!")
# Pode ter vários except except AnotherExceptionHere: # Rode este código se AnotherExceptionHere acontecer
# Bloco finally opcional finally: print(5 * "a")
Introdução à programação orientada a objetos em Python

Saída do tratamento de exceções

You can't add an integer to a string, but you can multiply them!
aaaaa
Introdução à programação orientada a objetos em Python

Lançando exceções

def make_list_of_ones(length):
    if length <= 0:
        # Mensagem personalizada se ocorrer ValueError
        # Interrompe o programa e lança o erro
       raise ValueError("Invalid length!")
    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("Invalid length!")
ValueError: Invalid length!
Introdução à programação orientada a objetos em Python

Exceções são classes

  • Exceções herdam de BaseException ou Exception
    BaseException
    +-- Exception
        +-- ArithmeticError                     
        |    +-- FloatingPointError
        |    +-- OverflowError
        |    +-- ZeroDivisionError              
        +-- TypeError
        +-- ValueError
        |    +-- UnicodeError
        |         +-- UnicodeDecodeError
        |         +-- UnicodeEncodeError
        |         +-- UnicodeTranslateError
        +-- RuntimeError
       ...
    +-- SystemExit
    ...
    
1 https://docs.python.org/3/library/exceptions.html
Introdução à programação orientada a objetos em Python

Exceções personalizadas

  • Herde de Exception ou uma de suas subclasses
  • Geralmente uma classe vazia
class BalanceError(Exception): 
    pass

class Customer: def __init__(self, name, balance): if balance < 0 : raise BalanceError("Balance has to be non-negative!") else: self.name = name self.balance = balance
Introdução à programação orientada a objetos em Python

Exceção no construtor

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("Balance has to be non-negative!")
BalanceError: Balance has to be non-negative!
Introdução à programação orientada a objetos em Python

Exceções encerram o programa

  • A exceção interrompeu o construtor → objeto não criado
cust
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    cust
NameError: name 'cust' is not defined
Introdução à programação orientada a objetos em Python

Capturando exceções personalizadas

try:
    cust = Customer("Larry Torres", -100)
except BalanceError:
    cust = Customer("Larry Torres", 0)
Introdução à programação orientada a objetos em Python

Vamos praticar!

Introdução à programação orientada a objetos em Python

Preparing Video For Download...