在Python中捕获imaplib异常(使用IMAPClient包)

Ars*_*ngh 3 python imaplib

我正在使用外部库IMAPClient.登录失败时,我看到此错误:imaplib.error: [AUTHENTICATIONFAILED] Authentication failed.

当我尝试except imaplib.error:我得到:AttributeError: 'module' object has no attribute 'error'

imaplib的文档说异常应该是IMAP4.error那么为什么IMAPClient会提升imaplib.error,我该如何捕获呢?

mat*_*ski 6

您看到的错误消息:

imaplib.error: [AUTHENTICATIONFAILED] Authentication failed.
Run Code Online (Sandbox Code Playgroud)

正在描述错误,因为它知道如何最好; 在异常发生时,异常类被称为"imaplib.error",因为无论是谁提出它都以这种方式描述它(稍后将详细介绍).我戳了一下,我想我已经找到了你:

Python 2.7.2 (default, Nov 14 2011, 19:37:59) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import imaplib
>>> imaplib.IMAP4.error
<class 'imaplib.error'>
Run Code Online (Sandbox Code Playgroud)

我打开了imaplib.py文件,发现了一个奇怪的异常抛出机制."IMAP4"是一个类,"error"是在IMAP4类中定义的类.Python似乎没有"嵌套"类 - 只是类定义.因此,一旦存在类"错误"的对象,它就是"错误"类的对象,它在范围"imaplib"中定义."error"类定义在"IMAP4"类lib定义中的事实与Python无关.另一方面,为了这样的对象存在之前描述类"错误" 的对象,您需要将其作为imaplib.IMAP4.error引用,以便Python找到您正在讨论的类的定义.

我知道,非常混乱,在我开始调查这个问题之前,我并不是真的知道这一切.这是一个简短的说明:

Python 2.7.2 (default, Nov 14 2011, 19:37:59) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class foo(object):
...   class bar(object):
...     pass
...   def b(self):
...     return bar()
... 
>>> bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'bar' is not defined
>>> foo.bar
<class '__main__.bar'>
>>> foo().bar()
<__main__.bar object at 0x10048dd10>
Run Code Online (Sandbox Code Playgroud)

基本上,你试图做一个非常合理的事情,但imaplib库处理异常抛出的方式有点奇怪,让你的生活变得困难.长话短说,你应该尝试抓住imaplib.IMAP4.error并继续你的生活.