【问题标题】:Exceptions and sqlite3异常和 sqlite3
【发布时间】:2014-11-08 05:42:00
【问题描述】:
import sqlite3
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
try:
    cursor.execute("INSERT INTO loctions VALUES('Hogwarts', 'Scotland'")
    cursor.execute("INSERT INTO characters VALUES('Albus', 'Dumbledore')")
    conn.commit()

except sqlite3.OperationalError:
    print "Oops! This was an operational error. Try again..."

except sqlite3.NameError:
    print "Name Error"

except sqlite3.ValueError:
    print "value error"

except sqlite3.IOError:
    print "IO error"

conn.close()

我正在尝试确定以上代码是否有效。也就是说,我的“try”子句之后可以有多个例外吗?

当我通过输入“python filename.py”运行此程序时,我看到“糟糕!这是一个操作错误。再试一次...”打印在我的终端中。

这是有道理的,因为我拼错了第一个表的名称(位置而不是位置),所以这是一个操作错误。

但我对如何强制出现名称错误或值错误感到困惑。

另外,当我注释掉“except sqllite3.OperationalError”子句时,我的终端出现了这个错误:

Traceback (most recent call last):
  File "sqle.py", line 14, in <module>
    except sqlite3.NameError:
AttributeError: 'module' object has no attribute 'NameError'

这是说没有sqlite3.NameError这样的东西吗?然而 sqlite3.OperationalError 是一回事。

我如何发现存在哪些类型的错误?

【问题讨论】:

    标签: python sql sqlite flask


    【解决方案1】:

    NameErrorValueErrorIOErrorbuiltin exceptions。不要用sqlite3. 限定他们:

    ...
    except NameError:
        print "Name Error"
    except ValueError:
        print "value error"
    except IOError:
        print "IO error"
    

    查看模块中定义了哪些异常(使用异常是Exception类的子类的属性):

    >>> import inspect
    >>> [name for name, value in vars(sqlite3).items()
         if inspect.isclass(value) and issubclass(value, Exception)]
    ['Warning', 'InternalError', 'ProgrammingError', ..., 'OperationalError']
    

    或咨询the module documentation

    【讨论】:

    • 这对任何其他包(例如 peewee)也非常有用。谢谢。
    猜你喜欢
    • 2019-09-17
    • 2011-07-15
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 2016-11-22
    相关资源
    最近更新 更多