首页 > 编程语言 > 详细

python中标准的异常捕获的层级

时间:2021-06-21 11:51:30      阅读:23      评论:0      收藏:0      [点我收藏+]

在python中捕获异常语法为:

try:
    语句1
    语句2
   ...
except 异常名 as  异常别名:
    语句1
    语句2
    ...
else:
  语句1
  语句2
  ...
finally:
  语句1
  ...

例子:

def divide(x, y):
  try:
      result = x / y
  except ZeroDivisionError:
      print("division by zero!")
  else:
     print("result is", result)
  finally:
     print("executing finally clause")

当要捕获的异常,无法预知异常名的时候,可以使用最顶层的基本异常来代替,这个异常是所有异常的基类,名为BaseException

如果是用户自定义异常,通常不应该直接继承这个类,而是继承它的一个子类:Exception

在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中标准的异常捕获的层级

原文:https://www.cnblogs.com/hyyx/p/14909562.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!