标签:memory mem isa 修复 syn cat src 出错 编写
try: print("try.....") r=10/0 print(‘result:‘,r) except ZeroDivisionError as e: print(‘except:‘,e) finally: print(‘finally...‘) print(‘End‘)
try如果执行出错,则后续代码不会继续执行,而是直接跳转到错误代码处。如果except捕捉到错误,则执行该except代码块,执行完后,如果有finally语句块,则执行finally语句块,然后结束。
当except后面语句后面有else且没有错误发生,则执行else语句块。
Python所有的错误都是由BaseException类派生的,如果错误由前面的except捕捉到了,则错误即使符合后面的except类型,也不会被检测到的。
Python异常基础图:
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的内置错误类型(ValueError, TypeError),我们自己也可以定义错误类型。
Python内置的try...except....finally用来处理错误十分方便,出错时,会分析错误信息并且定位错误发生的代码位置才是最关键的。
程序也可以主动抛出错误,让处理者来处相应错误,但是应该在文档中写清楚可能会抛出哪些异常,以及错误产生的原因。
标签:memory mem isa 修复 syn cat src 出错 编写
原文地址:https://www.cnblogs.com/pythonlearing/p/9755054.html