python 3-放出、異常のキャプチャ
4789 ワード
'''
: ,
:
1.traceback ( )
2.
3.
:
1. ( )
2.
:
AttributeError
, foo.x, foo x
IOError
/ ;
ImportError
;
IndentationError
( ) ;
IndexError
, x , x[5]
KeyError
KeyboardInterrupt
Ctrl+C
NameError
SyntaxError
Python , ( , )
TypeError
UnboundLocalError
, ,
ValueError
,
:
#
try:
except as : #
try , 。
else:
finally:
, ,
try:
1
2
……
except StopIteration:
……
else:
……
finally:
……
:assert
, ; , (AssertionError)
'''
# 1. ( )
try:
print('========>1')
print('========>2')
l = [1, 2, 3]
l[100] # IndexError
# , try
print('========>3')
d = {'x': 1, 'y': 2}
d['z'] # KeyError
print('========>4')
except IndexError as ie:
print('IndexError',ie)
print('other code')
# 2.
try:
print('========>1')
print('========>2')
d = {'x': 1, 'y': 2}
d['z'] # KeyError
print('========>3')
l = [1, 2, 3]
l[100] # IndexError
print('========>4')
except IndexError as ie:
print('IndexError',ie)
except KeyError as ke:
print('KeyError',ke)
#
except (IndexError,KeyError) as e:
print('Error',e)
print('other code')
# 3. Exception:
try:
print('========>1')
print('========>2')
d = {'x': 1, 'y': 2}
d['z'] # KeyError
print('========>3')
l = [1, 2, 3]
l[100] # IndexError
print('========>4')
except Exception as e:
print('Error',e)
print('other code')
# 4. + , 。 :
try:
print('========>1')
print('========>2')
d = {'x': 1, 'y': 2}
d['z'] # KeyError
print('========>3')
l = [1, 2, 3]
l[100] # IndexError
print('========>4')
except IndexError as ie:
print('IndexError',ie)
except KeyError as ke:
print('KeyError',ke)
except Exception as e:
print('Error',e)
print('other code')
# 5.else finally
try:
print('========>1')
print('========>2')
d = {'x': 1, 'y': 2}
d['z'] # KeyError
print('========>3')
l = [1, 2, 3]
l[100] # IndexError
print('========>4')
except IndexError as ie:
print('IndexError',ie)
except KeyError as ke:
print('KeyError',ke)
except Exception as e:
print('Error',e)
else:
print('else')
finally:
print('finally')
print('other code')
# 6.
raise TypeError(' ')
# 7.
try:
raise TypeError(' ')
except Exception as e:
print(e)
# 8.
class MyException(BaseException):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
try:
raise MyException(' ')
except MyException as me:
print(me)
# :assert
# , ; , (AssertionError)
print('1111')
l = [1,2,3,]
assert len(l)>5
print('22222222')
#
class People:
def __init__(self,name,age):
self.__name = name
self.__age = age
def get_interface(self):
print(self.__name,self.__age)
def set_inter(self,name,age):
try:
if not isinstance(name,str):
raise TypeError(' str ')
if not isinstance(age,int):
raise TypeError(' int ')
except TypeError as te:
print(te)
return te
self.__name = name
self.__age = age
p1 = People(100,100)
p1.get_interface()
p1.set_inter(110,101)
p1.get_interface()
p1.set_inter('name1','age1')
p1.get_interface()
p1.set_inter('name2',19)
p1.get_interface()