Как найти ошибку в коде vbs

I want to use VBScript to catch errors and log them (ie on error «log something») then resume the next line of the script.

For example,

On Error Resume Next
'Do Step 1
'Do Step 2
'Do Step 3

When an error occurs on step 1, I want it to log that error (or perform other custom functions with it) then resume at step 2. Is this possible? and how can I implement it?

EDIT: Can I do something like this?

On Error Resume myErrCatch
'Do step 1
'Do step 2
'Do step 3

myErrCatch:
'log error
Resume Next

asked Oct 1, 2008 at 14:04

apandit's user avatar

apanditapandit

3,3041 gold badge26 silver badges32 bronze badges

1

VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.

On Error Resume Next

DoStep1

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStep1: " & Err.Description
  Err.Clear
End If

DoStep2

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStop2:" & Err.Description
  Err.Clear
End If

'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0

The «On Error Goto [label]» syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn’t support this language feature so you have to use On Error Resume Next as described above.

answered Oct 1, 2008 at 14:11

Dylan Beattie's user avatar

Dylan BeattieDylan Beattie

53.5k35 gold badges128 silver badges197 bronze badges

5

Note that On Error Resume Next is not set globally. You can put your unsafe part of code eg into a function, which will interrupted immediately if error occurs, and call this function from sub containing precedent OERN statement.

ErrCatch()

Sub ErrCatch()
    Dim Res, CurrentStep

    On Error Resume Next

    Res = UnSafeCode(20, CurrentStep)
    MsgBox "ErrStep " & CurrentStep & vbCrLf & Err.Description

End Sub

Function UnSafeCode(Arg, ErrStep)

    ErrStep = 1
    UnSafeCode = 1 / (Arg - 10)

    ErrStep = 2
    UnSafeCode = 1 / (Arg - 20)

    ErrStep = 3
    UnSafeCode = 1 / (Arg - 30)

    ErrStep = 0
End Function

answered Apr 27, 2015 at 21:26

omegastripes's user avatar

omegastripesomegastripes

12.3k4 gold badges45 silver badges96 bronze badges

5

You can regroup your steps functions calls in a facade function :

sub facade()
    call step1()
    call step2()
    call step3()
    call step4()
    call step5()
end sub

Then, let your error handling be in an upper function that calls the facade :

sub main()
    On error resume next

    call facade()

    If Err.Number <> 0 Then
        ' MsgBox or whatever. You may want to display or log your error there
        msgbox Err.Description
        Err.Clear
    End If

    On Error Goto 0
end sub

Now, let’s suppose step3() raises an error. Since facade() doesn’t handle errors (there is no On error resume next in facade()), the error will be returned to main() and step4() and step5() won’t be executed.

Your error handling is now refactored in 1 code block

answered Jun 24, 2019 at 9:48

Cid's user avatar

CidCid

14.8k4 gold badges28 silver badges45 bronze badges

I’m exceptionally new to VBScript, so this may not be considered best practice or there may be a reason it shouldn’t be done this that way I’m not yet aware of, but this is the solution I came up with to trim down the amount of error logging code in my main code block.

Dim oConn, connStr
Set oConn = Server.CreateObject("ADODB.Connection")
connStr = "Provider=SQLOLEDB;Server=XX;UID=XX;PWD=XX;Databse=XX"

ON ERROR RESUME NEXT

oConn.Open connStr
If err.Number <> 0 Then : showError() : End If


Sub ShowError()

    'You could write the error details to the console...
    errDetail = "<script>" & _
    "console.log('Description: " & err.Description & "');" & _
    "console.log('Error number: " & err.Number & "');" & _
    "console.log('Error source: " & err.Source & "');" & _
    "</script>"

    Response.Write(errDetail)       

    '...you could display the error info directly in the page...
    Response.Write("Error Description: " & err.Description)
    Response.Write("Error Source: " & err.Source)
    Response.Write("Error Number: " & err.Number)

    '...or you could execute additional code when an error is thrown...
    'Insert error handling code here

    err.clear
End Sub

answered Feb 7, 2019 at 21:08

MistyDawn's user avatar

MistyDawnMistyDawn

8468 silver badges9 bronze badges

1

What @cid provided is a great answer. I took the liberty to extend it to next level by adding custom throw handler (like in javascript). Hope someone finds its useful.

option Explicit

Dim ErrorCodes
Set ErrorCodes = CreateObject("Scripting.Dictionary")
ErrorCodes.Add "100", "a should not be 1"
ErrorCodes.Add "110", "a should not be 2 either."
ErrorCodes.Add "120", "a should not be anything at all."

Sub throw(iNum)
    Err.Clear

    Dim key
    key = CStr(iNum)
    If ErrorCodes.Exists(key) Then
        Err.Description = ErrorCodes(key)
    Else
        Err.Description = "Error description missing."
    End If
    Err.Source = "Dummy stage"
    
    Err.Raise iNum 'raise a user-defined error
End Sub


Sub facade(a)
    if a=1 then
        throw 100
    end if

    if a = 2 then
        throw 110
    end if

    throw 120
End Sub

Sub Main
    on error resume next

        facade(3)

        if err.number <> 0 then
            Wscript.Echo Err.Number, Err.Description
        end if
    on error goto 0
End Sub

Main

answered Jul 13, 2022 at 20:05

PravyNandas's user avatar

PravyNandasPravyNandas

59711 silver badges12 bronze badges

Error Handling

Error handling does not involve finding
errors in your scripts. Instead, use error handling techniques to
allow your program to continue executing even though a potentially
fatal error has occurred. Ordinarily, all runtime errors that are
generated by the VBScript engine are fatal, since execution of the
current script is halted when the error occurs. Error handling allows
you to inform the user of the problem and either halt execution of
the program or, if it is prudent, continue executing the program.

The On Error Resume Next Statement

There are two main elements to error handling in VBScript. The first
is the On

Error statement,
which informs the VBScript engine of your intention to handle errors
yourself, rather than to allow the VBScript engine to display a
typically uninformative error message and halt the program. This is
done by inserting a statement like the following at the start of a
procedure:

On Error Resume Next

This tells the VBScript engine that, should an error occur, you want
it to continue executing the program starting with the line of code
which directly follows the line in which the error occurred. For
example, in the simple WSH script:

On Error Resume Next
x = 10
y = 0
z = x / y
Alert z

a “Cannot divide by Zero” error is generated on the
fourth line of code because the value of y
is 0. But because you’ve placed the On Error
statement in line 1, program execution continues with line 5. The
problem with this is that when an error is generated, the user is
unaware of it; the only indication that an error has occurred is the
blank Alert box (from line 5) that’s displayed for the user.

Tip

A particular On
Error statement
is valid until another On
Error
statement in the line of execution is encountered. This means that if
Function A contains an On Error statement, and
Function A calls Function B, but Function B does not contain an
On
Error statement, the error
handling from Function A is still valid. Therefore, if an error
occurs in Function B, it is the On
Error statement in Function A that handles the
error; in other words, when an error is encountered in Function B,
program flow will immediately jump to the line of code that followed
the call to Function B in Function A. When Function A completes
execution, the On
Error
statement it contains also goes out of scope. This means that, if the
routine that called Function A did not include an
On
Error statement, no error
handling is in place.

This is where the second element of VBScript’s error handling
comes in. VBScript includes an error object, named Err, which, when
used in conjunction with On
Error
Resume
Next, adds much more functionality to error
handling, allowing you to build robust programs and relatively
sophisticated error handling routines.

The Err Object

The Err object is part of the VBScript
language and contains information about the last error to occur. By
checking the properties of the Err object after a particular piece of
code has executed, you can determine whether an error has occurred
and, if so, which one. You can then decide what to do about the error
—you can, for instance, continue execution regardless of the
error, or you can halt execution of the program. The main point here
is that error handling using On Error and the Err
object puts you in control of errors, rather than allowing an error
to take control of the program (and bring it to a grinding halt). To
see how the Err object works and how you can use it within an error
handling regimen within your program, let’s begin by taking a
look at its properties and methods.

Err object properties

Like all
object properties, the properties of the Err object can be accessed
by using the name of the object, Err, the

dot (or period) delimiter, and the
property name. The Err object supports the following properties:

Number

The Number property is an integer value that
contains an error code value between
and 65535, representing the last error. If the value of
Err.Number is 0, no error has occurred.
The line of code like the following, then, can be used to determine
if an error has occurred:

If Err.Number <> 0 Then

Although the properties of the Err object provide information on the
last error to occur in a script, they do not do so permanently. All
the Err object properties, including the Number property, are set
either to zero or to zero-length strings after an End Sub, End
Function, Exit Sub or Exit Function statement. In addition, though,
you can explicitly reset Err.Number to
zero after an error by calling the Err object’s
Clear method. The WSH script in Example 4.8 illustrates the importance of resetting the
Err
object after an error occurs.

Example 4-8. Failing to Reset the Err Object

Dim x, y ,z

On Error Resume Next

x = 10
y = 0
z = x / y
If Err.Number <> 0 Then
   MsgBox "There's been an error #1"
Else
  MsgBox z
End IF

z = x * y
If Err.Number <> 0 Then
   MsgBox "There's been an error #2"
Else
   MsgBox z
End If

End Sub

The division by zero on the fifth line of the script in Example 4.8 generates an error. Therefore, the conditional
statement on line 6 evaluates to True, and an
error dialog is displayed. Program flow then continues at line 12.
Line 12 is a perfectly valid assignment statement that always
executes without error, but the Err.Number property still contains
the error number from the previous error in line 5. As a result, the
conditional statement on line 13 evaluates to
True, and a second error dialog is displayed.
Despite the two error messages, though, there’s only been a
single error in the script.

The Err object can be reset by using the Clear method (which is
discussed in the next Section 4.2.2.2).

Description

The Description property contains a string
that describes the last error that occurred. You can use the
Description property to build your own message box alerting the user
to an error, as the WSH script in Example 4.9 shows.

Example 4-9. Using the Description Property to Display Error Information

Dim x, y ,z
On Error Resume Next

x = 10
y = 0
z = x / y
If Err.Number <> 0 Then
   MsgBox "Error number " & Err.Number & ", " & _
          Err.Description & ", has occurred"
   Err.Clear
Else
   MsgBox z
End If

z = x * y
If Err.Number <> 0 Then
   MsgBox "Error No:" & Err.Number & " - " & _
          Err.Description & " has occurred"
   Err.Clear
Else
   Alert z
End If
Source

The Source property contains a string
expression that indicates the class name of the object or application
that generated the error. You can use the Source property to provide
users with additional information about an error; in particular,
about where an error occurred.

The value of the Source property for all errors generated within
scripted code is simply “Microsoft VBScript runtime
error.” This is true of all VBScript scripts, whether
they’re written for Active Server Pages, Windows Script Host,
Internet Explorer, or Outlook forms. Obviously, this makes the Source
property less than useful in many cases. However, you can assign a
value to the Source property in your own error handling routines to
indicate the name of the function or procedure in which an error
occurred. In addition, the primary use of the Source property is to
signal an error that is generated by some other object, like an OLE
automation server (like Microsoft Excel or Microsoft Word) or a COM
component.

Err object methods

The two
methods of the Err object allow you to raise or clear an error, in
the process simultaneously changing the values of one or more Err
object properties. The two methods are:

Raise

The Err.
Raise method allows you to generate a
runtime error. Its syntax is:[1]

where ErrorNumber is the numeric code for
the error you’d like to generate. At first glance, generating
an error within your script may seem like a very odd thing to want to
do! However, there are times, particularly when you are creating
large, complex scripts, that you need to test the effect a particular
error will have on your script. The easiest way to do this is to
generate the error using the Err.Raise method and providing the error
code to the ErrorNumber parameter, then
sit back and note how your error handling routine copes with the
error, what the consequences of the error are, and what side effects
the error has, if any. The client-side script in Example 4.10, for instance, allows the user to enter a
number into a text box, which is passed as the error code value to
the Err.Raise method. If the value of the error code is nonzero, an
Alert box opens that displays the error code and its corresponding
description. Figure 4.6, for instance, shows the
Alert box that is displayed when the user enters a value of 13 into
the text box.

Example 4-10. Calling the Err.Raise Method

<HTML>
<HEAD>
<TITLE>Using the Err Object</TITLE>
<SCRIPT LANGUAGE="vbscript">

Sub cmdButton1_OnClick
On Error Resume Next
errN = Document.frm1.errcode.value 
Err.Raise(errN)

If Err.Number <> 0 Then
 Alert "Error No:" & Err.Number & " - " & Err.Description
 Err.Number = 0
End If

End Sub

</SCRIPT>
</HEAD>
<BODY BGCOLOR="white">
<CENTER>
<H2>Generating an Error</H2>
<P>
<FORM NAME="frm1">
Enter an Error Code &nbsp;
<INPUT TYPE="text" NAME="errcode">
<INPUT TYPE="button" NAME="cmdButton1" VALUE="Generate Error">
</CENTER>
</BODY>
</HTML>

At present there is no definitive list of VBScript runtime error
codes available from Microsoft. Table 4.1 lists a
few of the most common
runtime
errors.

Tip

An Error Code Generator
(ERRCODES1.HTML,
ERRCODES1.ASP, and
ERRCODES1.VBS), which allows you to generate a
complete list of current VBScript error codes, can be found on the
O’Reilly Visual Basic web site at

http://vb.oreilly.com.

Table 4-1. Some Common VBScript Error Codes

Error Number

Description

5

Invalid procedure call

6

Overflow

7

Out of memory

9

Subscript out of range

11

Division by zero

13

Type mismatch

Generating a Type mismatch error at runtime

Figure 4-6. Generating a Type mismatch error at runtime

Clear

The Clear method clears the information
that the Err object is storing about the previous error; it takes no
parameters. It sets the values of
Err.Number to
and the Err object’s Source and Description properties to
a
null

string.

Get VBScript in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Студворк — интернет-сервис помощи студентам

Доброго времени суток! Задача такая: есть скрипт, который должен записать строковой параметр в один из разделов реестра. С этим все понятно. Но есть одно «но»! Как сделать так, чтобы скрипт действовал по такой схеме:

1. Проверяем, есть-ли уже это значение в разделе реестра;
2. Если есть, то переходим к дальнейшему выполнению скрипта;
3. Если нет, то создаем строковой параметр и просто выходим из скрипта не переходя к его выполнения.

Вроде все просто, но как-то не «воткну» в эти два оператора On Error Resume Next и On Error Goto 0 (примеров много, но все они для меня слишком сложны, т.к. я только-только начал штудировать скриптовый язык VB). Может кто подскажет простое решение для моей задачи? Заранее огромное спасибо!

  1. .ReadAll() the file to check
  2. Remove «Option Explicit» if necessary, prepend «Option Explicit : WScript.Quit 0»
  3. On Error Resume Next : Execute[Global] (modified) source : Handle Error

Update:

As intersum pointed out, I did not realize that the WScript.Quit will terminate the script that execute(global)s it. So using a shell can’t be avoided.

Proof of concept script:

Option Explicit

Dim goFS   : Set goFS = CreateObject("Scripting.FileSystemObject")
Dim goWS   : Set goWS = CreateObject("WScript.Shell")
Dim aFiles : aFiles   = Array("good.vbs", "bad.vbs")
Dim sFile
For Each sFile In aFiles
    WScript.Echo sFile, "==>", checkSyntax(sFile)
Next

Function checkSyntax(sFile)
  Dim sCode : sCode = goFS.OpenTextFile(sFile).ReadAll()
  WScript.StdOut.Write "  A " & sCode
  sCode = "Option Explicit : WScript.Quit 0 : " & sCode
  goFS.CreateTextFile("sctmp.vbs", True).WriteLine sCode
  WScript.StdOut.Write "  B " & goFS.OpenTextFile("sctmp.vbs").ReadAll()
  Dim oExec : Set oExec = goWS.Exec("cscript sctmp.vbs")
  Dim sOtp  : sOtp      = oExec.Stderr.ReadAll()
  If "" = sOtp Then
     checkSyntax = "ok"
  Else
     checkSyntax = sOtp
  End If
End Function

output:

cscript sc.vbs
  A WScript.Echo "good"
  B Option Explicit : WScript.Quit 0 : WScript.Echo "good"

good.vbs ==> ok
  A WScript.Echo "bad" : SomeSub(1, 2, 3)
  B Option Explicit : WScript.Quit 0 : WScript.Echo "bad" : SomeSub(1, 2, 3)

bad.vbs ==> M:libkurs0705xplsctmp.vbs(1, 73) Microsoft VBScript compilation error: Cannot use parentheses
when calling a Sub

Update II:

As can be seen from:

type bad.vbs
WScript.Echo "bad" : SomeSub 1, 2, 3

cscript bad.vbs
bad
M:libkurs0705xplbad.vbs(1, 22) Microsoft VBScript runtime error: Type mismatch: 'SomeSub'

a runtime error may occur after most of the script has executed (output of «bad»). To deal with such errors, you must

  1. design and implement robust programs
  2. do intensive tests
  3. implement rutime error handling

None of these requirements are ‘easy’ in VBScript.

Учебник VBScript №1: Обзор переменных VBScript 

Учебник VBScript №2: Условные операторы и циклы VBScript

Учебник VBScript №3: Процедуры VBScript

Учебник VBScript №4: Обработка ошибок VBScript и выполнение VBScript

Учебник VBScript №5: Строковые функции VBScript

VУчебник BScript №6: Функции даты VBScript

Учебник VBScript №7: Функции времени VBScript

Учебник VBScript №8: Функции массива VBScript

В этом руководстве по VBScript мы узнаем о процедурах VBScript, включая функции VBScript и подпроцедуры VBScript. Кроме того, в этом руководстве мы узнаем об обработке ошибок VBScript и подходах к выполнению VBScript.

Учебное пособие по VBScript #3: Процедуры VBScript

Процедуры VBScript:

Процедуры VBScript — это блок операторов, заключенный в особый ключевые слова для выполнения определенных действий. Процедуры VBScript могут принимать входные значения и возвращать выходное значение. Здесь входные значения представлены как аргументы. 

Процедуры VBScript в основном используются для профессиональной организации кода для повторного использования кода и лучшего обслуживания. Предположим, что в большой программе или кодах некоторая основная арифметическая операция выполняется многократно. Итак, если есть изменение в этой операции, нам нужно изменить все места, где она используется. Вместо того, чтобы делать то же самое, если мы напишем одну процедуру VBScript для той же операции и будем использовать ссылку на нее во всех местах, тогда нам нужно будет изменить код в одном месте. Таким образом, мы можем сократить усилия по обслуживанию скриптов.

На процедуры VBScript можно ссылаться с помощью ключевого слова «Call». Также VBScript позволяет вызывать любую процедуру без использования этого ключевого слова.

Преимущества процедур VBScript:

· Возможность повторного использования кода.

· Снижение усилий по обслуживанию скриптов.

· Лучшая читаемость кодов.

· Лучшая организация кодов.

Типы процедур VBScript:

Процедуры VBScript принимают входные данные, обрабатывают их и выполняют некоторые операции в зависимости от типов процедур. В целом процедуры VBScript подразделяются на два типа, которые указаны ниже: 

· Подпроцедура VBScript

· Процедура функции VBScript

Подпроцедуры VBScript:

Подпроцедуры VBScript группируют несколько операторов, не возвращая никаких выходных значений. Он может принимать входные данные в качестве аргументов. Этот тип процедур должен начинаться и заканчиваться ключевыми словами Sub и End Sub соответственно. Процедуры VBScript Sub могут принимать аргументы, но не возвращают никаких выходных значений. 

Пример. Здесь мы напишем небольшую подпроцедуру vbscript, которая принимает аргумент как предупреждающие сообщения и отображает его во всплывающем окне сообщения.

‘Call the vbscript sub procedure
Call displayAlert(“This is an example of vbscript sub procedure”) 
Sub displayAlert(alertMessage)
	Msgbox alertMessage
End Sub

Процедуры VBScript - подпроцедура VBScript

Процедуры VBScript — подпроцедура VBScript

Функция VBScript:

Если мы хотим выполнить блок операторов с возвратом каких-либо выходных значений, нам нужно использовать функции VBScript. В начале функций VBScript нам нужно использовать ключевое слово «Function» для определения имени функции, а в конце используется ключевое слово «End Function». Функции VBScript могут принимать как аргументы, так и возвращаемые значения. Чтобы вернуть значение из функции, значение должно быть присвоено имени функции перед закрытием функции.

Пример. В этом примере мы рассчитаем площадь круга с помощью функции vbscript. Здесь радиус будет передан в качестве аргумента функции VBScript и вернет область в качестве вывода.

Dim calcArea 'Вызов функции vbscript calcArea = calcCircleArea(7) msgbox "Площадь круга равна" & функция calcArea calcCircleArea(radius) dim pi, a pi = 22/7 a = pi*radius*radius calcCircleArea = a End Function
Output(Message Box): The area of the circle is 154

Аргументы ByRef и ByVal в процедурах VBScript:

Аргумент ByRef — Чтобы сохранить изменения, внесенные в аргумент, даже после вызова процедуры VBScript, мы должны отправить аргумент по ссылке (ByRef). Если при передаче аргументов в процедуры VBScript ничего не указано, по умолчанию он обрабатывается как переданный по ссылке. Ключевое слово ByRef используется для передачи аргумента по ссылке.

Пример ByRef — см. Код ниже, здесь аргумент Counter был передан в процедуру по ссылке. Первоначально он определен со значением четыре, а в процедуре он увеличивается на 1. Поскольку аргумент был передан по ссылке, значение аргумента будет равно пяти после вызова функции.

Function incrementCounter(ByRef Counter)
   Counter = Counter +1
   incrementCounter = Counter
End Function
Dim x
myCounter=4
call incrementCounter(myCounter)
msgbox myCounter

Output => 5

ByVal Аргумент — Когда аргумент передается по значению (ByVal), любые изменения, внесенные в значение аргумента в функциях VBScript, не сохранятся после вызова функции. Ключевое слово ByVal используется для передачи аргумента по значению.

Пример ByVal — см. Код ниже, здесь аргумент Counter был передан в процедуру по значению. Первоначально он определен со значением четыре, а в процедуре он увеличивается на 1. Поскольку аргумент был передан по значению, значение аргумента останется четвертым после вызова функции.

Function incrementCounter(ByVal Counter)
   Counter = Counter +1
   incrementCounter = Counter
End Function
Dim x
myCounter=4
call incrementCounter(myCounter)
msgbox myCounter

Output => 4

Учебное пособие по VBScript #4: Обработка ошибок VBScript и выполнение VBScript

Ошибки VBScript:

Ошибки VBScript — это не что иное, как необработанные события, которые не обрабатываются с помощью кода. В сценариях vb, если встречаются какие-либо события, которые не обрабатываются кодами, они рассматриваются как ошибки VBScript.

Типы ошибок VBScript: 

Ниже перечислены различные типы ошибок VBScript. 

Ошибки синтаксиса — Основными причинами этого типа ошибок VBScript являются неправильная структура скрипта, типографические ошибки, неправильное написание ключевых слов, синтаксические ошибки. Если синтаксические ошибки существуют, сценарий вообще не будет выполнен. Он появляется во время компиляции скрипта. 

Логические ошибки — Этот тип ошибок VBScript возникает из-за некоторых неожиданных событий, таких как сбой преобразования числа или даты из-за несоответствующих данных. Он появляется во время выполнения тестовых скриптов.

Ошибки VBScript

Процедуры VBScript — подпроцедура VBScript

Функция VBScript:

Если мы хотим выполнить блок операторов с возвратом каких-либо выходных значений, нам нужно использовать функции VBScript. В начале функций VBScript нам нужно использовать ключевое слово «Function» для определения имени функции, а в конце используется ключевое слово «End Function». Функции VBScript могут принимать как аргументы, так и возвращаемые значения. Чтобы вернуть значение из функции, значение должно быть присвоено имени функции перед закрытием функции.

Пример. В этом примере мы рассчитаем площадь круга с помощью функции vbscript. Здесь радиус будет передан в качестве аргумента функции VBScript и вернет область в качестве вывода.

Dim calcArea 'Вызов функции vbscript calcArea = calcCircleArea(7) msgbox "Площадь круга равна" & функция calcArea calcCircleArea(radius) dim pi, a pi = 22/7 a = pi*radius*radius calcCircleArea = a End Function
Output(Message Box): The area of the circle is 154

Аргументы ByRef и ByVal в процедурах VBScript:

Аргумент ByRef — Чтобы сохранить изменения, внесенные в аргумент, даже после вызова процедуры VBScript, мы должны отправить аргумент по ссылке (ByRef). Если при передаче аргументов в процедуры VBScript ничего не указано, по умолчанию он обрабатывается как переданный по ссылке. Ключевое слово ByRef используется для передачи аргумента по ссылке.

Пример ByRef — см. Код ниже, здесь аргумент Counter был передан в процедуру по ссылке. Первоначально он определен со значением четыре, а в процедуре он увеличивается на 1. Поскольку аргумент был передан по ссылке, значение аргумента будет равно пяти после вызова функции.

Function incrementCounter(ByRef Counter)
   Counter = Counter +1
   incrementCounter = Counter
End Function
Dim x
myCounter=4
call incrementCounter(myCounter)
msgbox myCounter

Output => 5

ByVal Аргумент — Когда аргумент передается по значению (ByVal), любые изменения, внесенные в значение аргумента в функциях VBScript, не сохранятся после вызова функции. Ключевое слово ByVal используется для передачи аргумента по значению.

Пример ByVal — см. Код ниже, здесь аргумент Counter был передан в процедуру по значению. Первоначально он определен со значением четыре, а в процедуре он увеличивается на 1. Поскольку аргумент был передан по значению, значение аргумента останется четвертым после вызова функции.

Function incrementCounter(ByVal Counter)
   Counter = Counter +1
   incrementCounter = Counter
End Function
Dim x
myCounter=4
call incrementCounter(myCounter)
msgbox myCounter

Output => 4

Учебное пособие по VBScript #4: Обработка ошибок VBScript и выполнение VBScript

Ошибки VBScript:

Ошибки VBScript — это не что иное, как необработанные события, которые не обрабатываются с помощью кода. В сценариях vb, если встречаются какие-либо события, которые не обрабатываются кодами, они рассматриваются как ошибки VBScript.

Типы ошибок VBScript: 

Ниже перечислены различные типы ошибок VBScript. 

Ошибки синтаксиса — Основными причинами этого типа ошибок VBScript являются неправильная структура скрипта, типографические ошибки, неправильное написание ключевых слов, синтаксические ошибки. Если синтаксические ошибки существуют, сценарий вообще не будет выполнен. Он появляется во время компиляции скрипта. 

Логические ошибки — Этот тип ошибок VBScript возникает из-за некоторых неожиданных событий, таких как сбой преобразования числа или даты из-за несоответствующих данных. Он появляется во время выполнения тестовых скриптов.

Ошибки VBScript

Ошибки VBScript

Обработка ошибок VBScript:

Невозможно обработать все неожиданные ошибки VBScript с помощью кодирования. Итак, обработка ошибок VBScript — это первоочередная задача. В первую очередь, есть один подход к обработке ошибки VBScript в сценариях. Этот подход представляет собой комбинацию использования операторов «При ошибке возобновить следующий» и свойства объекта Err.

При ошибке Возобновить следующие операторы: 

Он использовал операторы On-Error-Resume-Next; исключение можно обработать частично. При таком подходе блок тестового сценария должен запускаться с помощью операторов «On Error Resume Next». Это означает, что в случае какой-либо ошибки выполнение будет пропущено с текущего шага и перейдет к следующему шагу. После этого, проверив ошибку, мы сможем обрабатывать исключения. Важные ключевые слова —

· При ошибке возобновить следующий — В случае ошибки VBScript не выдаст сообщение об ошибке; вместо этого выполнение перейдет к следующему шагу.

· При ошибке Перейти к 0 — Он будет работать в обратном порядке по сравнению с указанным выше ключевым словом. Итак, после выполнения этого шага VBScript будет выдавать ошибки в случае каких-либо исключений.

· Ошибка. Описание — В нем хранится описание ошибки.

· Error.Number — Он содержит номер ошибки. Для успеха значение равно нулю.

· Error.Clear — Он сбрасывает объект ошибки.

 При ошибке Возобновить Далее 'оператор Vbscript 1 'оператор Vbscript 1 . . . . . Если error.number <> 0, то 'Проверка на наличие ошибки'..Обработать ошибку Else 'Условие успеха ничего обрабатывать не нужно Error.Clear End If On Error Goto 0

Подход к выполнению VBScript:

Существуют различные способы выполнения сценариев VBScripts. Наиболее часто используемые подходы —

  • Выполнить VBScript через файл .vbs
  • Выполнять VBScript как часть веб-разработки HTML

Выполнить VBScript через файл .vbs: Шаги для выполнения vbscript через файл .vbs:

  1. Запишите коды VBScript в простой плоский файл. Для создания файла можно использовать любой редактор, например, блокнот, Note Pad ++, Edit Plus и т. Д.
  2. Сохраните файл с расширением .vbs.
  3. Запустите файл, дважды щелкнув по нему.
  4. Тот же файл можно запустить из командной строки, используя полный путь к файлу. Команда для выполнения файла vbs: WScript » ».

В этом руководстве по vbscript мы используем этот подход для запуска всех демонстрационных сценариев vbscript.

Выполните VBScript как часть веб-страницы: В этом подходе нам нужно написать коды VBScript с тегом in in the web page. The syntax will be looks like below –

<script type="text/vbscript">
-	Vbscript statements …
</script>

Этот подход используется при разработке веб-страниц с использованием классического ASP. Также то же самое можно использовать в других технологиях, таких как PHP, JSP и т. Д.

Инструменты использует VBScript:  Основные инструменты, поддерживающие сценарии vbscripts: UFT, Excel Macro, Visual Basic, Classic ASP (сценарии на стороне клиента).

Вывод:

В этой статье о VBScript мы узнали о процедурах VBScript и обработке ошибок VBScript с помощью этого руководства. Мы надеемся, что это руководство очень помогло вам освежить в памяти основы написания сценариев VB. Чтобы получить дополнительную информацию о VBScripting, нажмите здесь.

Понравилась статья? Поделить с друзьями:
  • Как найти ошибку в cmd
  • Как найти ошибку в cbs log
  • Как найти ошибку в android studio
  • Как найти ошибку в 1 сезон
  • Как найти ошибку в коде java