首页 > 解决方案 > 继承基本 Python 错误异常对象(语法)

问题描述

在 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 认为的错误。(除了无效语法之外的任何东西都会有所帮助)

标签: pythonsqlvbaerror-handling

解决方案


我想这就是你要找的

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 异常的更多信息,请看这里


推荐阅读