简体   繁体   English

在python中处理多个异常?

[英]Handling multiple exceptions in python?

I want to pause a python script when Crtl + C is pressed but to handle the rest of exceptions with different code. 我想在按Crtl + C时暂停python脚本,但要用其他代码处理其余的异常。

If I got: 如果我得到:

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)

Won't second except go also for KeyboardInterrupt , isn't a keyboard interrupt supposed to be an exception? except KeyboardInterrupt ,它不会是第二个,难道键盘中断不应该是一个例外吗?

Won't second except go also for KeyboardInterrupt, isn't a keyboard interrupt supposed to be an exception? 除了KeyboardInterrupt之外,它不会是第二个,难道键盘中断不应该是一个例外吗?

Well, this is interesting... Apparently it is not a subclass of the Exception class, but is child to a superclass called BaseException . 好吧,这很有趣……显然,它不是 Exception类的子类,而是超类BaseException的子类。

Python's doc Built-in Exceptions explains why they implemented it this way: Python的文档“ 内置异常”解释了为什么以这种方式实现它:

The exception inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting. 异常继承自BaseException,以免被捕获Exception的代码意外捕获,从而防止解释器退出。

And it can be checked like this: 可以这样检查:

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

Nevertheless, even if you changed your last except block to catch a BaseException instead of a Exception , it would still not enter it (because your inner except KeyboardInterrupt avoids the exception to be thrown to the outer indentation or "parent" levels). 但是,即使您更改了最后一个except代码块以捕获BaseException而不是Exception ,它也不会输入(因为您的内部except KeyboardInterrupt避免了将异常抛出到外部缩进或“父”级别)。

In case you also removed this inner except KeyboardInterrupt block, the exception would be thrown to the outer indentation, which I assume it does not exist (given your indentation level) and the execution would terminate... 如果您还删除了except KeyboardInterrupt此内部块,则将异常抛出给外部缩进,我假设它不存在(给定您的缩进级别),并且执行将终止...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM