Python 异常处理 详解
1、错误和异常
1.1 错误 Error
- 逻辑错误:算法写错了,例如加法写成了减法
- 笔误:例如变量名写错了,语法错误
- 函数或类使用错误:其实这也属于逻辑错误
- 总之,错误是可以避免的
1.2 异常 Exception
- 异常就是意外情况
- 在没有出现上述错误的前提下,也就是说程序写的没有问题,但是在某些情况下,会出现一些意外,导致程序无法正常执行下去
- 例如,访问一个网络文件,突然断网了,这就是个异常,是个意外的情况
- 总之,异常是不可能避免的
1.3 总结
- 错误和异常:在高级编程语言中,一般都有错误和异常的概念,异常是可以捕获的,并被处理的,但是错误是不能被捕获的
- 一个健壮的程序,尽可能的避免错误,尽可能的捕获、处理各种异常
2、产生异常
-
1 raise 语句显式的抛出异常
-
2 Python 解释器自己检测到异常并引发它
-
3 程序会在异常抛出的地方中断执行,如果不捕获,就会提前结束程序(其实是终止当前线程的执行)
def foo(): print('before') print(1/0) # 捕获异常 print('after') foo() # ZeroDivisionError: division by zero def foo(): print('before') raise Exception('My Exception') # raise 主动抛出异常 print('after') foo() # Exception: My Exception
3、捕获异常
3.1 语法
try:
待捕获异常的代码块
except [异常类型]:
异常的处理代码块
3.2 示例 1
-
此例执行到
c = 1/0
时产生异常并抛出,由于使用了try...except
语句块则捕捉到了这个异常 -
异常生成位置之后语句块将不再执行,转而执行对应的
except
部分的语句 -
最后执行
try...except
语句块之外的语句def foo(): try: print('before') c = 1/0 print('after') except: print('error') print('catch the exception') foo() print('====== end ======')
before error catch the exception ====== end ======
3.3 示例 2
def foo():
try:
print('before')
print(1/0)
print('after')
except ArithmeticError: # 指定捕获的类型
print('error')
print('catch the exception')
foo()
print('====== end ======')
before
error
catch the exception
====== end ======
4、 异常类
4.1 Exception hierarchy
The class hierarchy for built-in exceptions is:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
|