代码写了不少,以前一直没有认真想过容错处理。直到代码应用到不同的工作环境的时候,出现了莫明其妙的错误才会想到这个问题,也许这就是所谓的半路出家的结果,没有系统的学过编程理论,汗。话题扯远了,下面说下AU3中调用WMI的出错处理。也就是在AU3编程调用COM对象的出错处理。
下面以AUTOIT3帮助的例子为例。
; ObjEvent example
; COM Error Handler example
$oIE=ObjCreate("InternetExplorer.Application.1")
; Create Internet Explorer application
$oMyError = ObjEvent("AutoIt.Error","MyErrFunc")
; Initialize a COM error handler
$oIE.UnknownMethod
; Deliberately call an undefined method
If @error then
Msgbox (0,"AutoItCOM test","Test passed:" & _
"We got an error number: " & @error)
Else
Msgbox (0,"AutoItCOM test","Test failed!")
Endif
Exit
; This is my custom defined error handler
Func MyErrFunc()
Msgbox(0,"AutoItCOM Test","We intercepted a COM Error !"&@CRLF&@CRLF & _
"err.description is: " &@TAB&$oMyError.description&@CRLF& _
"err.windescription:" &@TAB&$oMyError.windescription&@CRLF& _
"err.number is: " &@TAB&hex($oMyError.number,8)&@CRLF& _
"err.lastdllerror is: "&@TAB&$oMyError.lastdllerror&@CRLF& _
"err.scriptline is: " &@TAB&$oMyError.scriptline& @CRLF& _
"err.source is: " &@TAB&$oMyError.source&@CRLF& _
"err.helpfile is: " &@TAB&$oMyError.helpfile&@CRLF& _
"err.helpcontext is: " &@TAB&$oMyError.helpcontext)
Local $err = $oMyError.number
If $err = 0 Then $err = -1
SetError($err)
; to check for after this function returns
Endfunc
AUTOIT 的帮助例子永远是那么的详细和经典,为JON喝彩。废话了。哈。继续:
上边的例子是先用ObjCreateI创建一个Internet Explorer中的应用对象,然后马上定义了处理这个对象的解发事件,即 ObjEvent("AutoIt.Error","MyErrFunc") ,"AutoIt.Error"为AU3中内置的错误处理关键字,"MyErrFunc"为自定义函数;上边的例子中的MyErrFunc函数列出了调用COM对象中的所有Err 对象,这样在AU3中就可以方便的调用出错处理了,再也不会说有对象出错,软件退出的现象了。下边再写一个以显示连接远程计算机获得错误信息的代码为例:
Global $MyError,$RemoteComputer,$RemoteUser,$RemotePass
Global $objlocator, $objWMIService, $objlocator, $error
$MyError = ObjEvent("AutoIt.Error","MyErrFunc")
$RemoteComputer="netdisk"
$RemoteUser="admin"
$RemotePass="test"
$objlocator = ObjCreate("wbemscripting.swbemlocator")
$objWMIService = $objlocator.connectserver($RemoteComputer, _
"root/cimv2", $RemoteUser, $RemotePass)
$error=MyErrFunc()
If @error Then MsgBox(16,"错误", & _
"错误行数是:"&$error[2]&"行"&@CRLF &@CRLF & _
"错误代码为:"&$error[1]&@CRLF &@CRLF & _
"错误信息是:"&$error[3]&@CRLF &@CRLF)
Func MyErrFunc()
Local $MyRet[4]
$MyRet[0] = $MyError.number
$MyRet[1] = Hex($MyRet[0], 8)
$MyRet[2] = $MyError.scriptline
$MyRet[3] = $MyError.description
ConsoleWrite("### COM Error ! " & _
"Number: " & $MyRet[1] & _
" ScriptLine: " &$MyRet[2] & _
" Description:" & $MyRet[3] &@CRLF)
SetError(1)
Return $MyRet
Endfunc
上边代码详细的显示了出错的行数、出错信息,出错的代码,而出错信息和出错代码完全是系统返回的,可以直接上网查了,不用再担心不知道错误原因了!
如图所示:
1、连接远程计算机失败:
2、远程计算机用户名或者密码不对:
转贴请保留版权,文章出处:http://www.lunhui.net.cn/article.asp?id=12 |