1.什么是异常
异常与错误有区别:异常可以被捕获,而错误有时候无法被捕获,语法错误会被IDE检查到,但是逻辑错误无法被知晓;
异常的产生有两种方式:使用raise语句,显式的抛出异常,还有一种是由于代码错误,解释器抛出的异常,如果没有进行异常捕获,就会中断程序的运行;
2.如何捕获异常
try:
# 这里会抛出异常,因为0不能被整除
a = 1 / 0
except Exception:
print('异常')
捕捉异常可以使用try/except语句;
try: 需要被捕获异常的代码块;
except :处理捕获到的异常;
3.异常的参数
- 一个异常可以带上参数,可作为输出的异常信息参数,可以通过except语句来捕获异常的参数;
4.异常的继承关系
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
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
5.常用异常类介绍
BaseException:所有异常类的基类都是BaseException;
Exception:所有内建,非系统退出的异常类的基类,所有自定义异常类需要继承Exception;
SystemExit:解释器请求退出;
KeyboardInterrupt:用户中断执行(通常是输入^C);
Exception:常规错误的基类;
自定义异常
class XKDException(ArithmeticError):
def __init__(self, ):
pass
6.一个完整的异常捕获
try:
a = 1
b = 0
result = a / b
except ArithmeticError:
print('ArithmeticError')
except Exception as e:
print(e)
else:
print('ok')
finally:
print(a)
print(b)