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)
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")