如何使用 Python 中的参数处理异常

How to handle exception with parameters in Python

在 Python 3.x 中,处理带有参数的异常的正确语法是什么。 我专门尝试处理记录在 this page.

上的 WriteError

我正在编写代码来处理它:

   except pymongo.errors.WriteError(err, code, dtls):
       logging.error("DB Write Error. err={}; code={}; dtls={}".format(err, code, dtls))

这不起作用。

我什至看过 Erros and Exceptions 文档。但是在那里找不到它。

你能告诉我处理这类异常的正确方法吗?

您首先捕获错误,然后检查其属性(如果不是您想要处理的异常,则重新引发异常)。异常内容没有模式匹配。

except pymongo.errors.WriteError as exc:
    logging.error("DB WriteError. err={}; code={}; dtls={}".format(exc.err, exc.code, exc.dtls))

except 块只需要异常的类型。当然,如果您愿意,您可以在块内使用它的属性:

except pymongo.errors.WriteError as e:
   logging.error("DB Write Error. err={}; code={}; dtls={}".format(e.err, e.code, e.dtls))