我们在编码的过程中,难免会遇到一些错误和异常, 这时候程序会异常退出,并且会抛出错误信息:
比如:
print(1/0) ''' 输出: Traceback (most recent call last): File "D:/PythonStudy/errors.py", line 3, in <module> print(1/0) ZeroDivisionError: division by zero '''
我们尝试让1 去除0,结果系统报错了异常 ‘ZeroDivisionError: division by zero’, 表示不能被零除。
Python内置许多异常,当出现这些问题时,会提示我们并中断运行,python3.7中主要有以下的异常:
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
有关内置异常的详细描述可以参考python的相关文档,链接如下: https://docs.python.org/zh-cn/3/library/exceptions.html#bltin-exceptions
Python提供了一套方式,用来捕获和处理错误和异常:
使用try....except...finally来对可能存在的错误进行处理:
#-*- coding:utf-8 -*- try: print(1/0) except ZeroDivisionError: print('Can not division 0, happen ZeroDivisionError') finally: print('Go to next step') ''' 输出: Can not division 0, happen ZeroDivisionError Go to next step '''
通过上面的例子,我们可以看到,代码首先执行try里的code,如果遇到了指定的错误,那么就执行except中的代码, 处理完毕后执行finally中的代码。
在每个代码块中,支持各种判断和迭代,其工作的流程结构如下:
除了系统内置的错误,我们也可以在代码中主动抛出一些错误:
#-*- coding:utf-8 -*- name = 'ralf' if name != 'rachel': raise Exception('The name is not ralf') ''' 输出: Traceback (most recent call last): File "D:/PythonStudy/errors.py", line 4, in <module> raise Exception('The name is not ralf') Exception: The name is not ralf '''
我们也可以通过继承Exception base class,自定我们自己的错误类型:
#-*- coding:utf-8 -*- class NameError(Exception): def __init__(self, level, message): self.level = level self.message = message try: name = 'ralf' if name != 'rachel': raise NameError('Error', 'Name is not right') except NameError as e: print(e.level) print(e.message) ''' 输出: Error Name is not right '''