2021-04-20 07:11:13 +00:00
|
|
|
# test subclassing a native exception
|
|
|
|
|
|
|
|
|
2014-04-29 00:28:31 +00:00
|
|
|
class MyExc(Exception):
|
|
|
|
pass
|
|
|
|
|
2021-04-20 07:11:13 +00:00
|
|
|
|
2014-04-29 00:28:31 +00:00
|
|
|
e = MyExc(100, "Some error")
|
|
|
|
print(e)
|
2014-05-01 22:51:25 +00:00
|
|
|
print(repr(e))
|
2014-04-29 00:28:31 +00:00
|
|
|
print(e.args)
|
2014-05-01 23:30:28 +00:00
|
|
|
|
|
|
|
try:
|
2018-08-17 05:46:04 +00:00
|
|
|
raise MyExc("Some error", 1)
|
2014-05-01 23:30:28 +00:00
|
|
|
except MyExc as e:
|
|
|
|
print("Caught exception:", repr(e))
|
|
|
|
|
|
|
|
try:
|
2018-08-17 05:46:04 +00:00
|
|
|
raise MyExc("Some error2", 2)
|
2014-05-01 23:30:28 +00:00
|
|
|
except Exception as e:
|
|
|
|
print("Caught exception:", repr(e))
|
|
|
|
|
|
|
|
try:
|
|
|
|
raise MyExc("Some error2")
|
|
|
|
except:
|
|
|
|
print("Caught user exception")
|
2021-04-20 07:11:13 +00:00
|
|
|
|
|
|
|
|
|
|
|
class MyStopIteration(StopIteration):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
print(MyStopIteration().value)
|
|
|
|
print(MyStopIteration(1).value)
|
|
|
|
|
|
|
|
|
2021-06-29 07:32:18 +00:00
|
|
|
class Iter:
|
|
|
|
def __iter__(self):
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __next__(self):
|
|
|
|
# This exception will stop the "yield from", with a value of 3
|
|
|
|
raise MyStopIteration(3)
|
|
|
|
|
|
|
|
|
|
|
|
def gen():
|
|
|
|
print((yield from Iter()))
|
|
|
|
return 4
|
|
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
next(gen())
|
|
|
|
except StopIteration as er:
|
|
|
|
print(er.args)
|
|
|
|
|
|
|
|
|
2021-04-20 07:11:13 +00:00
|
|
|
class MyOSError(OSError):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
print(MyOSError().errno)
|
|
|
|
print(MyOSError(1, "msg").errno)
|