文档详情

Python程序设计-清华大学出版社-董付国第8章 异常处理结构与程序调试.ppt

发布:2017-05-23约1.16万字共39页下载文档
文本预览下载声明
第8章 异常处理结构与程序调试 8.1 什么是异常 x, y = 10, 5 a = x / y print A Traceback (most recent call last): File pyshell#2, line 1, in module print A NameError: name A is not defined 8.1 什么是异常 10 * (1/0) Traceback (most recent call last): File stdin, line 1, in ? ZeroDivisionError: division by zero 4 + spam*3 Traceback (most recent call last): File stdin, line 1, in ? NameError: name spam is not defined 2 + 2 Traceback (most recent call last): File stdin, line 1, in ? TypeError: Cant convert int object to str implicitly 8.1 什么是异常 语法错误和逻辑错误不属于异常,但有些语法错误往往会导致异常,例如由于大小写拼写错误而访问不存在的对象。 当Python检测到一个错误时,解释器就会指出当前流已无法继续执行下去,这时候就出现了异常。异常是指因为程序出错而在正常控制流以外采取的行为。 异常分为两个阶段:第一个阶段是引起异常发生的错误;第二个阶段是检测并处理阶段。 不建议使用异常来代替常规的检查,如if...else判断。 应避免过多依赖于异常处理机制。 当程序出现错误,python会自动引发异常,也可以通过raise显示地引发异常。 8.2 Python中的异常类 BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError +-- 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 +-- SyntaxError | +-- IndentationError | +-- TabError +--
显示全部
相似文档