处理导入的模块例外

时间:2016-10-23 02:23:18

标签: python exception

如何处理Python中的模块特定异常?

例如,如果我想捕获python中sqlite3模块抛出的错误,我会在{}中放置什么来处理该异常?

ifp=open('Some_File.txt','r')
all_text=''
for line in ifp:
    all_text=all_text+line.decode('utf-8','errors'='Ignore').encode('utf-8')
print(''+all_text)
ifp.close()

3 个答案:

答案 0 :(得分:1)

答案已经在这里,How to reference an exception class in Python?,尽管标题不知道答案。

我以一个简单的导入类语法问题(当前形式)阅读了该问题。 SQLLite docs page on exceptions给出了一个示例,但没有描述如何显式实现SQLLite异常。而且不应该。我相信应该在Python.org exceptions页面上举一个例子,但是您甚至找不到那里的例子-就是这样:

  

“许多标准模块定义了自己的异常以报告错误   它们定义的功能中可能会发生这种情况。有关课程的更多信息   在Classes一章中进行了介绍。”

您点击链接,现在进入 Python类的第一页。 *点心*如果您是新手,可以开始阅读,如果您还没有回到Google,那么您可以读到

  

顺便说一句 [我的重点],我将单词属性用于点后面的任何名称-   例如,在表达式z.real中,real是   对象z。严格来说,对模块中名称的引用是   属性参考:在表达式modname.funcname中,modname是一个   模块对象和funcname是它的一个属性。在这种情况下   恰好是模块之间的直接映射   属性和模块中定义的全局名称:它们共享   相同的名称空间!

现在您已经排序了,对吧?我不知道。我对术语'dot notation'(以及较不常见的“点语法”)很熟悉,但是这里没有使用。当所有路牌都掉下来时,可以让人慢慢走动。当“异常”页面可以为您提供这个简单的示例时,您需要花费很多时间

import <module>

try:
    ...
except <module>.<exception>:
    ...

关于混乱的另一种想法。

通常使用这种语法从模块导入特定的函数或类,

from [module] import [function/class]

新手可能很难看清简单的答案。我认为这种常用语法在心理模型中造成了空白,这使得将模块导入语法与模块使用语法连接起来很困难。 Here's a great answer on this topic which is a much better citation for Module Exception Importing than the Classes link above

答案 1 :(得分:0)

查看sqlite3模块上的文档,以下内容应该可以正常工作

try:
    #code that throws sqlite3.Error exception
catch sqlite3.Error:
    #code to handle error

这只是此特定模块可以抛出的几个错误之一,并且可以通过将上述sqlite3.Error部分替换为所需的异常来处理每个错误。

答案 2 :(得分:0)

正确的模块文档列出了模块可能引发的模块特定异常,因此模块用户可以理解并可能捕获它们。 sqlite3 docs包含此内容。

12.6.5. Exceptions

exception sqlite3.Warning
    A subclass of Exception.

exception sqlite3.Error
    The base class of the other exceptions in this module.
    It is a subclass of Exception.

exception sqlite3.DatabaseError
    Exception raised for errors that are related to the database.

exception sqlite3.IntegrityError
    Exception raised when the relational integrity of the database
    is affected, e.g. a foreign key check fails. It is a subclass
    of DatabaseError.

exception sqlite3.ProgrammingError
    Exception raised for programming errors, e.g. table not found
    or already exists, syntax error in the SQL statement, wrong
    number of parameters specified, etc. It is a subclass of
    DatabaseError.

你可以抓住其中任何一个。例如,套接字模块doc有一个类似的部分。