一 异常概述:
(1)异常功能:
*错误处理:程序运行时发出错误,python就会引发异常,可以在程序代码中捕捉和处理异常、或者忽略异常,如果忽略,python默认的异常处理行为将启动:停止程序,打印出错信息。
*事件通知。
*特殊情况处理。
*终止行为:try/finally语句可确保一定会执行需要的结束运算。
*非常规控制流程:异常是一种高级“goto”,可实现非常规的控制流程。
(2)引发异常:
*异常能由oython或程序引发。
*通过raise语句手动触发。格式:raise <instance>或raise <class>或raise,不包含异常名称的raise是重新引发当前异常。
*使用assert语句触发。格式:assert<test>,<data>,如果test计算为false则python会引发AssertionError异常,data是异常的额外数据。
(3)处理异常:
*格式:
try:
<statement>
except(name1):
<statement>
except(name2,name3):
<statement>
except(name4) as <data>:
<statement>
except:
<statement>
else:
<statement>
finally:
<statement>
*except(name):捕获列出的异常。
*except::捕获所有未列出的异常,放在所有except语句的最后。
*else:没有引发异常时执行。只能有一个else语句。
*finally:不管异常是否发生都执行。
(4)自定义异常类:
*用户自定义的异常类需继承内置异常类Exception。
二 内置异常类(Built-in Exception):
(1) 内置异常类的继承层次:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EnvironmentError
| +-- IOError
| +-- OSError
| +-- WindowsError (Windows)
| +-- VMSError (VMS)
+-- EOFError
+-- ImportError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning