newguy
newguy

Reputation: 617

If Run can't find file then continue anyway

In VBScript I am running a program I expect is likely to be in the PATH or current directory of the script. However if it is not in those places and cannot be found the script stops with error "The system cannot find the file specified". The command is not crucial and I would like to continue even in that case. Is that possible?

Upvotes: 0

Views: 274

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

As @Noodles pointed out in the comments you can use On Error Resume Next to have the interpreter hand over error handling to you/your code, and then "handle" the error by glossing over it:

Set sh = CreateObject("WScript.Shell")
...
On Error Resume Next
sh.Run "unimportant.exe", 0, True
On Error Goto 0
...

If you want to be a little more diligent and have the script fail if other errors occur add a routine to check the error number and quit after displaying an error message if it's neither 0 nor 0x80070002:

Set sh = CreateObject("WScript.Shell")
...
On Error Resume Next
sh.Run "unimportant.exe", 0, True
If Err.Number <> 0 And Err.Number <> &h80070002 Then
  WScript.Echo Trim("[0x" & Hex(Err.Number) & "] " & Err.Description)
  WScript.Quit 1
End If
On Error Goto 0
...

Be very careful when using On Error Resume Next, though. Use it sparingly, and disable it again (On Error Goto 0) as soon as possible. Contrary to popular belief the statement doesn't magically make errors go away. It just hands full responsibility for checking and handling errors over to you. Basically it's the VBScript term for "shut up, I know what I'm doing".

Upvotes: 1

Related Questions