如何捕获imaplib.abort异常?为何模块提示无该属性?
IMAPlib异常捕获困惑:明明抛出了
abort却找不到这个属性? 我的代码片段
import imaplib ... try: M.expunge() M.close() M.logout() except imaplib.abort as e: print("IMAP abort")
报错信息
Traceback (most recent call last): File "/home/xxx/anaconda3/lib/python3.6/imaplib.py", line 1014, in _command_complete typ, data = self._get_tagged_response(tag) File "/home/xxx/anaconda3/lib/python3.6/imaplib.py", line 1126, in _get_tagged_response self._check_bye() File "/home/xxx/anaconda3/lib/python3.6/imaplib.py", line 929, in _check_bye raise self.abort(bye[-1].decode(self._encoding, 'replace')) imaplib.abort: IMAP session state is inconsistent, please relogin. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "mailstats/autoresponder.py", line 224, in <module> M.close() File "/home/xxx/anaconda3/lib/python3.6/imaplib.py", line 456, in close typ, dat = self._simple_command('CLOSE') File "/home/xxx/anaconda3/lib/python3.6/imaplib.py", line 1191, in _simple_command return self._command_complete(name, self._command(name, *args)) File "/home/xxx/anaconda3/lib/python3.6/imaplib.py", line 1016, in _command_complete raise self.abort('command: %s => %s' % (name, val)) imaplib.abort: command: CLOSE => IMAP session state is inconsistent, please relogin. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "mailstats/autoresponder.py", line 226, in <module> except imaplib.abort as e: AttributeError: module 'imaplib' has no attribute 'abort'
我的疑问
既然imaplib模块没有abort属性,为何在_check_bye方法的第929行能抛出self.abort()?我该如何捕获该异常?
问题根源
你观察得特别仔细!这里的关键在于:abort并不是imaplib模块的顶层属性,而是IMAP4类的内部嵌套异常类。
源码里的self.abort,其中self是IMAP4类的实例(也就是你代码里的M),所以self.abort实际指向的是IMAP4.abort这个嵌套在类里的异常,而不是直接挂在imaplib模块下的属性。这就是为什么你直接写imaplib.abort会报错找不到,但源码里用self.abort能正常抛出异常的原因。
正确的捕获方法
有两种简单的方式可以正确捕获这个异常:
通过IMAP4类访问异常
直接引用IMAP4类下的abort异常:import imaplib ... try: M.expunge() M.close() M.logout() except imaplib.IMAP4.abort as e: print(f"IMAP abort occurred: {e}")通过实例的类型访问异常
如果你已经有了IMAP连接实例M,也可以用type(M)来获取它的类,再访问abort:try: M.expunge() M.close() M.logout() except type(M).abort as e: print(f"IMAP abort occurred: {e}")
顺便提一句,imaplib里的其他异常比如error、readonly也是同样的逻辑,都是IMAP4类的内部嵌套类,捕获时都需要通过IMAP4类来访问哦。
内容的提问来源于stack exchange,提问作者vy32
相关产品推荐
相关产品推荐

