参考资料:
1. 《Python基础教程》
2. http://www.runoob.com/python/python-exceptions.html
Python用异常对象(exception object)来表示异常情况。当Python无法正常处理程序时就会引发异常。如果异常对象并未被处理或捕捉,程序就会用所谓的回溯终止执行。
为了引发异常,可以使用一个类(Exception类或其子类)或实例参数调用raise语句。
raise Exception
raise Exception('Hello world')
Python内建的异常可以用以下方式查看:
import exceptions
dir(exceptions)
结果:
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__doc__', '__name__', '__package__']
异常处理使用实例1:
try:
1/0
except NameError:
print "Unknown variable."
except ZeroDivisionError:
print "Divided by zero"
else:
print "That went well."
finally:
print "Cleaning up."
结果:
异常处理使用实例2:
try:
1/0
except (NameError, ZeroDivisionError):
print "Unknown variable or divided by zero."
else:
print "That went well."
finally:
print "Cleaning up."
结果: