在Python中处理多个异常?

0 投票
1 回答
560 浏览
提问于 2025-04-18 04:25

我想在按下 Crtl+C 时暂停一个 Python 脚本,但想用不同的代码来处理其他的异常。

如果我写了:

except KeyboardInterrupt:
    print '\nPausing...  (Hit ENTER to continue, type quit to exit.)'
    try:
        response = raw_input()
        if response == 'quit':
            break
        print 'Resuming...'
    except KeyboardInterrupt:
        print 'Resuming...'
        continue        

except Exception, e:
    print traceback.print_exc()
    continue
    sleep(170)

那么第二个 except 不也会处理 KeyboardInterrupt 吗?键盘中断不应该算是一种异常吗?

1 个回答

1

第二个 except 不会对 KeyboardInterrupt 有效吧?键盘中断不应该是个异常吗?

这真有意思……显然,KeyboardInterrupt 不是 Exception 类的子类,而是一个叫做 BaseException 的父类的子类。

Python 的文档 内置异常 解释了为什么这样实现:

这个异常继承自 BaseException,是为了避免被那些捕获 Exception 的代码意外捕获,从而阻止解释器退出。

你可以这样检查:

>>> issubclass(KeyboardInterrupt, Exception)
False
>>> issubclass(KeyboardInterrupt, BaseException)
True
>>> issubclass(Exception, BaseException)
True

不过,即使你把最后的 except 块改成捕获 BaseException 而不是 Exception,它仍然不会进入这个块(因为你内部的 except KeyboardInterrupt 阻止了异常向外层缩进或“父级”层级抛出)。

如果你还去掉了这个内部的 except KeyboardInterrupt 块,异常就会抛到外层缩进,我猜那里的代码并不存在(根据你的缩进级别),执行就会终止……

撰写回答