Wyjątki

  • obsługa błędów, których się nie spodziewamy
  • należy obsługiwać jak najwęższy odcinek wyjątków
  • EAFP (Easier to ask for forgiveness than permission ) vs LBYL (Look before you leap)

In [ ]:
import random
try:
    open("{}.txt".format(random.random()), "r")
except FileNotFoundError as e:
    print("nie ma pliku!")
    print(e)
finally:
    print("zawsze sie wykonuje!")

In [ ]:
import random
def foo():
    try:
        #return open("{}.txt".format(random.random()), "r")
        return 5
    except FileNotFoundError as e:
        print("nie ma pliku!")
        print(e)
    finally:
        print("zawsze sie wykonuje!")
        
print(foo())

In [ ]:
try:
    [1, 2, 3, 4]['a']
    [1, 2, 3, 4][10]
except IndexError as e:
    print("poza zakresem")
except TypeError as e:
    print("zly typ indexu")
    print(e)

In [ ]:
try:
    [1, 2, 3, 4]['a']
    [1, 2, 3, 4][10]
except (IndexError, TypeError) as e:
    print("oops!")
    raise e

In [ ]:
class Error(Exception):
    pass

class SpecificError(Error):
    def __init__(self, msg, msg2):
        self.error_msg = msg
        self.error_2 = msg2
        
def foo():
    try:
        raise SpecificError("oops!", "ehh!")
    except Error as e:
        print(e)
        
foo()

In [ ]:
def divide_numbers(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("nie dziel przez zero!")
    else:
        print("podzielilem: ", result)
    finally:
        print("finnaly")

divide_numbers(5, 2)
divide_numbers(5, 0)

With

  • opakowanie kodu w metody __enter__(self) i __exit__
  • __exit__ wywoływane na koniec bloku kodu

with open("asdf.txt", "r" as f):

....


In [ ]:
class CustomContextManager(object):
    def __enter__(self):
        print("wejscie w metode enter")
        return 5
    
    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is not None:
            print("co zrobic na exception?")
        print (exc_type, exc_value, traceback)
        print("koniec bloku exit")
        
with CustomContextManager() as number:
    raise NotImplementedError
    print(number)

In [ ]:
class CustomContextManager(object):
    def __enter__(self):
        print("wejscie w metode enter")
        return 5
    
    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is not None:
            raise ValueError
        print("koniec bloku exit")
        
with CustomContextManager() as number:
    raise NotImplementedError
    print(number)

In [ ]:
class CustomContextManager(object):
    def __enter__(self):
        print("wejscie w metode enter")
        return 5
    
    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is not None:
            raise ValueError
        print("koniec bloku exit")
    
try:
    with CustomContextManager() as number:
        raise NotImplementedError
        print(number)
except ValueError:
        print("supress ValueError")
        print(number)

In [ ]:
class CustomContextManager(object):
    def __enter__(self):
        print("wejscie w metode enter")
        return 5
    
    def __exit__(self, exc_type, exc_value, traceback):
        print("koniec bloku exit")
        return True
    
try:
    with CustomContextManager() as number:
        raise NotImplementedError
        print(number)
except NotImplementedError:
        print("supress NotImplementedError")