异常捕获

在Python中,所有的异常都必须继承自 BaseException 类。

Exception hierarchy

The class hierarchy for built-in exceptions is:

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使用try、except、else、finally关键字来捕获和处理异常。

语法如下:

可能产生异常的代码写在try块中。try块在执行过程中一旦发生异常,try块中剩下的代码不会执行。

try:
    block_try

except块用于定义当某种异常发生时所要执行的代码。except有几种形式:

  • 第一种是except指定当某种异常发生时,执行其块内代码。
  • 第二种是一条except可以捕获多种异常。
  • 第三种是捕获的异常可以被转换为一个变量Var。
  • 第四种是捕获任何异常。

当try块中发生异常时,从上到下逐个检查except块。当匹配到时,进入该except块进行异常处理,并且忽略其它except块。

except Exception1:
    block_when_exception1_happen

except (Exception2, Exception3, Exception4):
    block_when_exception2_or_3_or_4_happen

except Exception5 as Var:
    block_when_exception5_happen

except:
    block_for_any_exceptions

else是可选块,用于定义当try块中没有发生异常时的处理。

else:
    block_for_no_exceptions

finally是可选块,无论try块中是否有异常发生,其中的代码都会执行。

finally:
    block_anyway

rasie语句

  • 用于主动触发异常
语法:raise Exception('args')

>>> raise NameError('HiThere')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: HiThere
try:
    raise NameError('HiThere')
except NameError:
    print('An exception flew by!')
    # raise
import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
# except OSError as err:
#     print("OS error: {0}".format(err))
#     raise
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

assert语句

  • 用于检查表达式是否为真
  • 如果为假,则抛出AssertionError
语法:assert expression1 [,expression2]

>>> assert 0,'hh'
Traceback (most recent call last):
  File "te.py", line 1, in <module>
    assert 0,'hh'
AssertionError: hh

自定义异常

  • 必须(直接或间接)继承自Exception类
  • 只能主动触发
class FileError(OSError):
    pass

try:
    raise FileError('Test Error')
except FileError as e:
    print(e)
    # raise

参考文档
https://docs.python.org/3/library/exceptions.html
https://docs.python.org/3/library/exceptions.html#exception-hierarchy
https://docs.python.org/3/tutorial/errors.html#handling-exceptions
https://docs.python.org/3/tutorial/errors.html#raising-exceptions
https://docs.python.org/3/reference/simple_stmts.html#raise
https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement
https://docs.python.org/3/reference/compound_stmts.html#the-try-statement

posted @ 2017-10-04 01:41  KeithTt  阅读(283)  评论(0编辑  收藏  举报