1 异常处理
import sys
try:
f = open("myfile.txt")
s = f.readline()
i = int(s.strip())
# except OSError as err:
# print("OS error: {0}".format(err))
# except ValueError:
# print("could not convert data to an integer")
except (OSError,ValueError): #(error1,error2),异常元组
print("an error occurred")
except:#通配异常
print("unexpected error:",sys.exc_info()[0]) #print prompt message
raise #将异常继续抛出,给上层处理
else:#没有发生异常
print("there is no error or execpetion in the programming code")
2 抛出异常
#python使用raise语句抛出一个指定的异常
try:
raise ValueError("HiThere")
except ValueError:
print("an exception flew by")
raise #如果你只想知道这是否抛出了一个异常,
# 并不想去处理它,那么一个简单的 raise 语句就可以再次把它抛出
3 用户自定义异常
#用户自定义异常
#你可以通过创建一个新的exception类来拥有自己的异常。
# 异常应该继承自 Exception 类,或者直接继承,或者间接继承,
class MyError(Exception):
def __init__(self,value):#类 Exception 默认的 __init__() 被覆盖。
self.value = value
def __str__(self):
return repr(self.value)
try:
raise MyError(2*2)
except MyError as e:
print("My Exception occurred,value:",e.value)
#当创建一个模块有可能抛出多种不同的异常时,
# 一种通常的做法是为这个包建立一个基础异常类,然后基于这个基础类为不同的错误情况创建不同的子类:
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
""" Exception raised for errors in the input
Attributes:
expression--input expression in which the error occurred
message --explanation of the error
"""
def __init__(self,expression,message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not allowed
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self,previous,next,message):
self.previoud = previous
self.next = next
self.message = message
4 定义清理行为
>>> def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
5 预定义的清理行为
#一些对象定义了标准的清理行为,无论系统是否成功的使用了它,一旦不需要它了,那么这个标准的清理行为就会执行
for line in open("myfile.txt"):
print(line,end="") #这段代码的问题是,当执行完毕后,文件保持打开的转态,并没有关闭
with open("myfile.txt") as f:
for line in f:
print(line,end="") #关键词 with 语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行他的清理方法