python语法31[异常处理]
一 基本的异常处理
def TestTryException():
try:
f = open('myfile.txt')
s = f.readline()
f.close()
i = int(s.strip())
except IOError as ioerror :
print (ioerror)
except ValueError as valueerror:
print (valueerror)
except:
print ("Unexpected error")
else:
print (i)
finally:
print ("always running")
#TestTryException()
try:
f = open('myfile.txt')
s = f.readline()
f.close()
i = int(s.strip())
except IOError as ioerror :
print (ioerror)
except ValueError as valueerror:
print (valueerror)
except:
print ("Unexpected error")
else:
print (i)
finally:
print ("always running")
#TestTryException()
使用方式为try...except...else...finally,其中else和finally是可选项,finally不管是否有异常抛出总是会被执行。
二 自定义exception
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def TestMyException():
try:
raise MyError(2*2)
except MyError as e:
print (e)
#TestMyException()
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def TestMyException():
try:
raise MyError(2*2)
except MyError as e:
print (e)
#TestMyException()
自定义的exception需要从python的Exception类继承,使用raise来抛出异常。
完!