Errors and Exceptions
官方文档:https://docs.python.org/3.5/tutorial/errors.html
python中所有的异常都继承自BaseException类。
1.1 Syntax Errors
1.2 Exceptions
https://docs.python.org/3.5/library/exceptions.html
1.3 Handling Exception
使用try语句:
>>> while True: ... try: ... x = int(input("Please enter a number: ")) ... break ... except ValueError: ... print("Oops! That was no valid number. Try again...")
except也可以使用元组:
... except (RuntimeError, TypeError, NameError): ... pass
最后一个except可以省略异常名exception name,此时就跟通配符一样的作用(包含所有其他的异常)。
基于此,可以在最后一句except中打印异常提示并可重新raise对应的异常:
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: print("Unexpected error:", sys.exc_info()[0]) raise
还可以在try...except语句后使用else语句,适用于try后没发生相应异常又需要继续完成某种操作的情况:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
异常handler不仅能够捕捉try语句中的异常,也可以捕捉try语句内被调用函数的异常(嵌套的非直接调用的函数产生的异常也行):
>>> def this_fails():
... x = 1/0
...
>>> try:
... this_fails()
... except ZeroDivisionError as err:
... print('Handling run-time error:', err)
...
Handling run-time error: division by zero
1.4 Raising Exceptions
raise语句可以人为的让某个异常"发生":
>>> raise NameError('HiThere') Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: HiThere
raise的参数只有一个,即为一个异常的实例名或异常类名(当然,这个异常也是继承自Exception类的),
其实,当一个异常类被raise的时候,会自动调用它的构造函数“悄悄的”进行实例化:
raise ValueError # shorthand for 'raise ValueError()'
1.5 User-defined Exception
所有异常类都继承自Exception类。
通常的做法是先建立一个继承自Exception的Eroor,再根据不同的异常建立不同的异常类(继承Eroor):
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.previous = previous
self.next = next
self.message = message
1.6 Defineing Clean-up Actions
使用finally语句:
>>> try:
... raise KeyboardInterrupt
... finally:
... print('Goodbye, world!')
...
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
1.7 Predefined Clean-up Actions
with语句的使用:
with open("myfile.txt") as f:
for line in f:
print(line, end="")