Python公开课 - 异常处理

前言

在代码开发的过程中,经常或碰到一些错误异常情况,对于Python来说,自有一套规范的处理体系

try...except...finally...

现在高级语言都会使用try catch机制来捕获处理程序运行时候的各种异常,下面举一个除零异常的例子:

try:
    print('try...')
    r = 15 / 0
    print('result:', r)
except ZeroDivisionError as e:
    print('except:', e)
finally:
    print('finally...')
print('END')

输出:
try...
except: division by zero
finally...
END

示例说明:

  • try - 程序正常逻辑的代码
  • except - 捕获异常后处理的代码
  • finally - 不过如何都要执行的代码

当然如果我们不知道具体是啥异常的时候,可以使用一个通用异常类Exception来表示

try:
    print('try...')
    r = 15 / 0
    print('result:', r)
except Exception as e:
    print('except:', e)
finally:
    print('finally...')
print('END')

输出:
try...
('except:', ZeroDivisionError('integer division or modulo by zero',))
finally...
END

错误堆栈

在实际运行的过程中,如果直接将异常输出,往往只能获取到错误信息,而无法看到由哪块代码产生的错误,也就是需要查看错误堆栈,有几种方式可以实现

通过logging模块

import logging

def calc(s):
    return s/0

def main():
    try:
        a = calc(5)
    except Exception as e:
        logging.exception(e)

main()
print('END')


输出:
Traceback (most recent call last):
  File "test5.py", line 8, in main
    a = calc(5)
  File "test5.py", line 4, in calc
    return s/0
ZeroDivisionError: division by zero
END

通过trackback模块

import traceback

def calc(s):
    return s/0

def main():
    try:
        a = calc(5)
    except Exception as e:
        traceback.print_exc()

main()
print('END')


输出:
Traceback (most recent call last):
  File "test6.py", line 8, in main
    a = calc(5)
  File "test6.py", line 4, in calc
    return s/0
ZeroDivisionError: division by zero
END

自定义异常并抛出

class ShortInputException(Exception):
    def __init__(self, length, atleast):
        self.length = length
        self.atleast = atleast

try:
    s = input('please input:')
    if len(s) < 3:
        raise ShortInputException(len(s), 3)
except ShortInputException as e:
    print('输入长度是%s,长度至少是%s' %(e.length, e.atleast))
else:
    print('nothing...')

如果输入字符长度小于3,那么将会抛出 ShortInputException 异常,在Python中是通过raise关键字来进行异常抛出

相关阅读