首页 > 解决方案 > Python/Django:如何确定要在“except”语句中指定的类?

问题描述

我正在使用我继承的一些 Python/Django 代码。其中有一个由 try 块包围的 DB 调用,并带有一个“except Exception ex”语句来捕获所有异常。我想更有选择性,只捕获我预期的异常类型。通过检查捕获的异常对象,我可以判断它是“DatabaseError”类型。

下面代码中的注释显示了我尝试过的许多事情,基于谷歌搜索问题并在此处搜索,以及 Python 在我尝试它们时给我的错误。最令人沮丧的是,我在人们说有效的代码网络上找到了很多示例,这看起来就像我正在尝试的那样。但我发现的代码示例通常不包含“导入”行。

我怀疑我需要导入更多的东西,但我不知道是什么。

import cx_Oracle
## import cx_Oracle.DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
## from cx_Oracle import DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
. . .
    connection = connections['ims_db']

    sqlUpdateQuery = "SELECT * FROM LOCKING WHERE IDENT={0} AND KEY_ID='SL_KEY' FOR UPDATE NOWAIT".format(self.serviceUid)
    cursor = connection.cursor()
    try:
        cursor.execute(sqlUpdateQuery)

    # this gets the error "Undefined variable 'Database'"
    ## except Database.DatabaseError as dbe3:

    # this gets the error "Undefined variable 'Oracle'"
    ## except Oracle.DatabaseError as dbe2:

    # this gets the error "Module 'cx_Oracle' has no 'DatabaseError' member"
    ## except cx_Oracle.DatabaseError as dbe:

    # this gets the error "Undefined variable 'DatabaseError'"
    ## except DatabaseError as dbe:

    # this gets the error "Catching an exception which doesn't inherit from BaseException: cx_Oracle"
    ## except cx_Oracle as dbe:

    # this gets the error "Module cx_Oracle has no '_error' member"
    ## except cx_Oracle._Error as dbe:

    except Exception as ex:
        # This gets the error "Module cx_Oracle has no 'DatabaseError' member"
        ## if isinstance(ex, cx_Oracle.DatabaseError) :

        # This gets the error "Undefined variable 'DatabaseError'"
        ## if isinstance(ex, DatabaseError) :

        className = type(ex).__name__
        # This logs "... class = DatabaseError ..."
        log.error("Exception (class = {1}) while locking service {0}".format(self.serviceUid, className))
        args = ex.args
        arg0=args[0]
        # arg0ClassName is "_Error"
        arg0ClassName = type(arg0).__name__
        code = arg0.code
        # codeClassName is "int"
        codeClassName = type(code).__name__
        msg = "Exception, code = {0}".format(code)
        log.debug(msg)
        raise

标签: pythonexceptionexception-handlingcx-oracle

解决方案


正确的语法如下:

try:
    cur.execute("some_sql_statement")
except cx_Oracle.DatabaseError as e:
    error, = e.args
    print("CONTEXT:", error.context)
    print("MESSAGE:", error.message)

您可以在此处找到的一些示例(如 TypeHandlers.py)中看到该语法:https ://github.com/oracle/python-cx_Oracle/tree/master/samples 。

尝试运行示例并使用它们来查看是否可以解决您的问题。如果没有,请在此处创建一个包含完整可运行示例的问题:https ://github.com/oracle/python-cx_Oracle/issues 。


推荐阅读