【问题标题】:Inherit Base Python Error Exception Object (syntax)继承基本 Python 错误异常对象(语法)
【发布时间】:2021-03-15 12:05:51
【问题描述】:

在 Visual Basic 中,有一个继承的基础对象可有效用于错误调试目的。 Python中的“Err”对象是否有等价物?

Dim Msg As String  
' If an error occurs, construct an error message.  
On Error Resume Next   ' Defer error handling.  
Err.Clear  
Err.Raise(6)   ' Generate an "Overflow" error.  
' Check for error, then show message.  
If Err.Number <> 0 Then  
    Msg = "Error # " & Str(Err.Number) & " was generated by " _  
        & Err.Source & ControlChars.CrLf & Err.Description  
    MsgBox(Msg, MsgBoxStyle.Information, "Error")  
End If 

例如:

def exec_sproc(sql,cnxn):
   try:
      cursor=cnxn.cursor()
      cursor.execute(sql)
      cnxn.commit()
      cursor.close()
   except(err):
      print("error: {0}".format(err))

有一个建议可以试试

   except Exception,e: print str(e)

我得到一个无效的语法,因为 'e' 没有定义,或者在前面的例子中 err 显示为无效的语法。

Python 中的基本错误对象是什么?在大多数示例中,演示的是用户定义的自定义错误,而不是编写返回实际“Python”错误的代码。如果我知道错误是什么,我宁愿不犯。相反,向我展示 Python 认为的错误。 (除了无效语法之外的任何东西都会有所帮助)

【问题讨论】:

  • 您可以使用expect 和本例中的错误名称expect Exception: 来绕过错误或在出现错误时打印一些内容这是您要查找的内容吗?
  • 至于您收到错误的建议,因为没有变量/函数称为e,只需执行print("e") 并且它会起作用,并且您的expect 函数中还有一个错字应该是expect Exception as err: print(f"there is an {err} error")
  • 您的语法错误是因为 except Exception,e: 是 Python 2 语法。使用as 而不是逗号。

标签: python sql vba error-handling


【解决方案1】:

我猜这就是你要找的东西

def exec_sproc(sql,cnxn):
    try:
        cursor=cnxn.cursor()
        cursor.execute(sql)
        cnxn.commit()
        cursor.close()
    except Exception as err:
        print("error: {0}".format(err))

有关 Python 异常的更多信息,请查看here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-14
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多