Обработка ошибок vbs

На чтение 8 мин Просмотров 1.1к. Опубликовано

В этой статье мы рассмотри обработку ошибок в языке VBScript, а именно объектErr, конструкцию On Error Resume Next и On Error Goto 0. Конструкция VBScript On Error Resume Next включает обработку ошибок, а On Error Goto 0 отменяет их обработку.

Объект Err не нуждается в предварительном объявлении, и доступен всегда, давайте рассмотри его методы и свойства:

  • Description — данное свойство содержит описание ошибки.
  • Number — содержит целое число – номер ошибки. Если значение свойства Number ровно нулю – значит, ошибка отсутствует.
  • Source — свойство содержит название приложения, в котором возникла ошибка.

Методы

Clear – полная очистка информации об ошибке. Стоит обратить внимание, что информация об ошибке автоматически очищается при выполнении операторов On Error Resume Next, Exit Sub и Exit Function.

Raise(number, [source, description]) – данный метод позволяет генерировать собственную ошибку времени выполнения. Видим, что тут можно задать параметры, аналогичные по своей принадлежности свойствам самого объекта Err. Видим, что тут является обязательным только первый параметр.

Хорошо, теперь давайте рассмотри четыре примера на языке vbscript.

Пример 1

'------------------------------------------------------------------------------
' vbscript on error resume next
' произойдет вычисление только для первых 3 значений
' on_error_1.vbs
'------------------------------------------------------------------------------
 
Option Explicit
 
'включаем обработку ошибок
On Error Resume Next
 
dim MyArr(8), icount, Result, msgErr, msg 
 
' заполняем массив 
MyArr(0) = 5 
MyArr(1) = -3 
MyArr(2) = 15 
MyArr(3) = 0 
MyArr(4) = 2 
MyArr(5) = 6 
MyArr(6) = 0 
MyArr(7) = -1 
 
icount=0
msg=""
msgErr = "Ошибка!!!" & vbCrLf
 
'циклично делим число 15 на каждый элемент массива
Do  
     result=15/MyArr(icount)    
     If Err.Number <> 0 Then   
                 msgErr=msgErr & "Код ошибки: " & Err.Number & vbCrLf &_
                 "Описание: " & Err.Description & vbCrLf &_
                 "Приложение: " & Err.Source & vbCrLf
                 result = msgErr          
                 msgErr=""
     end if
     icount = icount+1
     msg=msg & Result & vbCrLf & vbCrLf
Loop While (icount < 8)
 
MsgBox msg

В данном примере мы создали массив из 8 элементов, каждый из которых является числом, два элемента – являются нулями. В цикле do…loop (работа данного цикла рассмотрена в статье Урок 7 по VBScript: Циклы do…loop и while…wend) идет деление числа 15 на каждый элемент массива (Урок 9 по VBScript: Массивы). Так как мы не включили в данном примере очистку информации об ошибке, то произойдёт деление только первых трёх значений, а всё остальное будет принято за ошибку.

Пример 2

'------------------------------------------------------------------------------
' vbscript on error resume next
' Вычисления не произойдут
' on_error_2.vbs
'------------------------------------------------------------------------------
 
Option Explicit
 
'включаем обработку ошибок
On Error Resume Next
 
dim MyArr(8), icount, Result, msgErr, msg 
 
' заполняем массив 
MyArr(0) = 5 
MyArr(1) = -3 
MyArr(2) = 15 
MyArr(3) = 0 
MyArr(4) = 2 
MyArr(5) = 6 
MyArr(6) = 0 
MyArr(7) = -1 
 
icount=0
msg=""
msgErr = "Ошибка!!!" & vbCrLf
 
'циклично делим число 15 на каждый элемент массива
Do  
     result=15/MyArr(icount)    
     If Err.Number <> 0 Then   
                 msgErr=msgErr + "Код ошибки: " & Err.Number & vbCrLf &_
                 "Описание: " & Err.Description & vbCrLf &_
                 "Приложение: " & Err.Source & vbCrLf
                 result = msgErr          
                 msgErr=""
                 ' Отменяем обработку ошибок!!!
                 On Error Goto 0
     end if
     icount = icount+1
     msg=msg & result & vbCrLf & vbCrLf
Loop While (icount < 8)
 
MsgBox msg

Тут мы дополнительно использовали конструкцию On Error Goto 0, которая отключает обработку ошибок. Это приведёт к тому, что никакие вычисления не будут произведены, и при запуске сценария автоматически произойдёт ошибка времени выполнения.

Скачать архив с примерами

Пример 3

'------------------------------------------------------------------------------
' on error resume next vbscript
' Правильный подход обработки ошибок
' on_error_3.vbs
'------------------------------------------------------------------------------
 
Option Explicit
 
'включаем обработку ошибок
On Error Resume Next
 
dim MyArr(8), icount, Result, msgErr, msg 
 
' заполняем массив 
MyArr(0) = 5 
MyArr(1) = -3 
MyArr(2) = 15 
MyArr(3) = 0 
MyArr(4) = 2 
MyArr(5) = 6 
MyArr(6) = 0 
MyArr(7) = -1 
 
icount=0
msg=""
msgErr = "Ошибка!!!" & vbCrLf
 
'циклично делим число 15 на каждый элемент массива
Do  
     'Очищаем информацию об ошибке
     Err.Clear
 
     result=15/MyArr(icount)    
     If Err.Number <> 0 Then   
                 msgErr=msgErr + "Код ошибки: " & Err.Number & vbCrLf &_
                 "Описание: " & Err.Description & vbCrLf &_
                 "Приложение: " & Err.Source & vbCrLf
                 result = msgErr          
                 msgErr=""
     end if
     icount = icount+1
     msg=msg & result & vbCrLf & vbCrLf
Loop While (icount < 8)
 
MsgBox msg

В этом примере мы сделали все правильно, так как вначале цикла прописали Err.Clear, который очищает информацию о предыдущих ошибках.

Ну и наконец четвертый пример, тут мы генерируем собственное описание ошибки.

Пример 4

'------------------------------------------------------------------------------
' on error resume next vbscript
' генерация собственной ошибки
' on_error_4.vbs
'------------------------------------------------------------------------------
 
Option Explicit
 
'включаем обработку ошибок
On Error Resume Next
 
dim MyArr(8), icount, Result, msgErr, msg 
 
' заполняем массив 
MyArr(0) = 5 
MyArr(1) = -3 
MyArr(2) = 15 
MyArr(3) = 0 
MyArr(4) = 2 
MyArr(5) = 6 
MyArr(6) = 0 
MyArr(7) = -1 
 
icount=0
msg=""
msgErr = "Ошибка!!!" & vbCrLf
 
'циклично делим число 15 на каждый элемент массива
Do  
     'Очищаем информацию об ошибке
     Err.Clear
     result=15/MyArr(icount)    
     If Err.Number <> 0 Then   
                 Err.Raise 100, "текущий сценарий", "пробуем делить на ноль"
                 msgErr=msgErr + "Код ошибки: " & Err.Number & vbCrLf &_
                 "Описание: " & Err.Description & vbCrLf &_
                 "Приложение: " & Err.Source & vbCrLf
                 result = msgErr          
                 msgErr=""
     end if
     icount = icount+1
     msg=msg & result & vbCrLf & vbCrLf
Loop While (icount < 8)
 
MsgBox msg

Давайте подытожим сказанной в данной статье…. Должен сказать, что материал получился довольно сухим на предмет обзора, это и не удивительно — большую часть занимают примеры программного кода. В целом, мы рассмотрели внутренний объект Err, который содержит методы и свойства для обработки исключительных ситуаций в сценариях на языке VBSCRIPT.

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 badge27 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.7k35 gold badges130 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.4k4 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

15k4 gold badges30 silver badges46 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

8568 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

60711 silver badges12 bronze badges

Материал из GedeminWiki

Перейти к: навигация,
поиск

VBScript имеет весьма скудные встроенные средства обработки ошибок времени выполнения, которые сводятся к двум операторам:

 On Error GoTo 0
 On Error Resume Next

Первый – отключает обработку ошибок (состояние по-умолчанию). Если ошибка случится, то на экран будет выдано сообщение и выполнение текущей процедуры или функции прекратится.

При включенном режиме On Error Resume Next, ошибка не приводит к прерыванию выполнения кода и программист имеет возможность самостоятельно разобраться с ней. Информация об ошибке содержится в глобальном встроенном объекте Err. Ниже приводится описание его свойств и методов:

Description 
Текстовое описание ошибки.
HelpContext 
Номер топика в файле справки, который будет открыт, если пользователь воспользуется клавишей F1 в окне сообщения об ошибке.
HelpFile 
Имя файла справки.
Number 
Целочисленный номер ошибки. 0 означает отсутствие ошибки.
Source 
Наименование приложения, в котором произошла ошибка.

Методы:

Clear 
Очищает все свойства объекта, сбрасывает информацию об ошибке. Обратите внимание, что объект Err автоматически очищается при выполнении следующих операторов: On Error Resume Next, Exit Sub, Exit Function.
Raise 
Генерирует ошибку времени выполнения. Полный формат вызова: Err.Raise(number, source, description, helpfile, helpcontext).

Только первый параметр (номер ошибки) является обязательным. Если опущены, значения остальных параметров подставляются из соответствующих свойств объекта.

Обработку ошибок проиллюстрируем на примере кода, который в цикле запрашивает у пользователя строку и пытается преобразовать ее в дату. Если введенная строка не является датой, то на экран выводится сообщение. Цикл повторяется, пока пользователь не введет корректную дату.

 Dim InputD, InputS
 On Error Resume Next
 Do
   Err.Clear
   InputS = InputBox("Введите дату")
   If IsNumeric(InputS) Then
     Err.Number = vbObjectError + 1
   Else
     InputD = CDate(InputS)
   End If
   If Err.Number <> 0 Then
   Application.MessageBox _
     "Неверный формат даты! Повторите ввод.", _
     "Ошибка", vbOkOnly + vbExclamation + vbSystemModal
   End If
 Loop Until Err.Number = 0
 On Error Goto 0

См. также

  • Использование TCreator

(Error Handling, Debugging Scripts)

Error Handling using VBScript:

Handling expected and unexpected Errors

> Expected Errors:

Whenever we use Invalid input then we can expect Errors.

Note: We use Invalid input for Negative Testing.

> Unexpected Errors

i) Resource missing

ii) Insufficient Resource

iii) Resource Response

How to Handle Errors:

i) Using Conditional Statements

ii) Using some built in Functions

iii) Using Exit Statement

iv) Using Option Explicit Statement

v) On Error Statement
Etc…

i) Using Conditional Statements

If Not Dialog(“Login”).Exist(3) Then
SystemUtil.Run “C:\Program Files\HP\Unified Functional Testing\samples\flight\app\flight4a.exe”
End If
Dialog(“Login”).Activate
Dialog(“Login”).WinEdit(“Agent Name:”).Set “asdf”
Dialog(“Login”).WinEdit(“Password:”).SetSecure “556fa5806c0b76ea4259c8e27e7c9af850b72f13”
Dialog(“Login”).WinButton(“OK”).Click
————————————————–
‘Working with multiple instance of Application

SystemUtil.Run “C:\Program Files\HP\Unified Functional Testing\samples\flight\app\flight4a.exe”
Dialog(“text:=Login”, “index:=0”).Activate
Dialog(“text:=Login”, “index:=0”).WinEdit(“attached text:=Agent Name:”).Set “asdf”
Dialog(“text:=Login”, “index:=0”).WinEdit(“attached text:=Password:”).SetSecure “556fa5806c0b76ea4259c8e27e7c9af850b72f13”
Dialog(“text:=Login”, “index:=0”).WinButton(“text:=OK”).Click
——————————————–
‘Working with multiple instantce of Application
Dialog(“text:=Login”, “index:=0”).Activate
Dialog(“text:=Login”, “index:=0”).WinEdit(“attached text:=Agent Name:”).Set “Hyderabad”
———————————
Note: Latest Application instance index is 0, oldest one index is n-1.

Browser(“CreationTime:=1”).close

We can work with multiple browsers using “CreationTime” property, latest browser creation time is n-1.

ii) Using VBScript Built in Functions

Examples:
Dim num1, num2
num1 = InputBox(“Enter Num1 value”)
num2 = InputBox(“Enter Num2 value”)

Msgbox “Addition of num1, num2 is: “& Cint (num1) + Cint (num2)
————————————-
Dim num1, num2
num1 = Cint (InputBox(“Enter Num1 value”))
num2 = Cint (InputBox(“Enter Num2 value”))

Msgbox “Addition of num1, num2 is: “& num1 + num2
—————————————————
Dim a, b
a = “abc”
b = “xyz”

If a > b Then
Msgbox “A is a Big Number”
Else
Msgbox “B is a Big Number”
———————————–
Dim a, b

a = InputBox(“Enter a Value”)
b = InputBox(“Enter b Value”)

If IsNumeric(a) = True And IsNumeric(b) Then
If Cint (a) > Cint (b) Then
Msgbox “A is a Big Number”
Else
Msgbox “B is a Big Number”
End if
Else
Msgbox “Invalid Input”
End If
————————————
‘Verify Data size and Data Type, display only 10 digit numeric value.
Dim MobileNumber

MobileNumber = InputBox(“Enter Mobile Number”)

If Len(MobileNumber) = 10 And IsNumeric(MobileNumber) = True Then
Msgbox MobileNumber
Else
Msgbox “Invalid Input”
End If
——————————————–
‘Check Data Range and accept the value is in between 21 to 35 only
Dim age
age = InputBox(“Enter Age”)

If IsNumeric (age) = True Then
If Cint(age) >= 21 And Cint(age) <= 35 Then
Msgbox “Accepted”
Else
Msgbox “Not Accepted”
End If
Else
Msgbox “Invalid Type of Data”
End If

iii) Using Exit Statement

It is used to Terminate Loops.

Ex:

Exit For

Exit Do
——————————————
‘ Terminate For loop
For OrderNumer = 20 To 30 Step 1
Window(“Flight Reservation”).Activate
Window(“Flight Reservation”).WinButton(“Button”).Click
Window(“Flight Reservation”).Dialog(“Open Order”).WinCheckBox(“Order No.”).Set “ON”
Window(“Flight Reservation”).Dialog(“Open Order”).WinEdit(“Edit”).Set OrderNumer
wait 2
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click

If Window(“Flight Reservation”).Dialog(“Open Order”).Dialog(“Flight Reservations”).Exist(3) Then
Window(“Flight Reservation”).Dialog(“Open Order”).Dialog(“Flight Reservations”).WinButton(“OK”).Click
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“Cancel”).Click
Window(“Flight Reservation”).WinButton(“Button_2”).Click
Reporter.ReportEvent micWarning, “Res”, “Up to “& OrderNumer-1 &” Orders only Exist”
Exit For
End If
Next
———————————–
‘ Terminate Do loop
OrderNumer = 20
Do Until OrderNumer > 30
Window(“Flight Reservation”).Activate
Window(“Flight Reservation”).WinButton(“Button”).Click
Window(“Flight Reservation”).Dialog(“Open Order”).WinCheckBox(“Order No.”).Set “ON”
Window(“Flight Reservation”).Dialog(“Open Order”).WinEdit(“Edit”).Set OrderNumer
wait 2
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click

If Window(“Flight Reservation”).Dialog(“Open Order”).Dialog(“Flight Reservations”).Exist(3) Then
Window(“Flight Reservation”).Dialog(“Open Order”).Dialog(“Flight Reservations”).WinButton(“OK”).Click
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“Cancel”).Click
Window(“Flight Reservation”).WinButton(“Button_2”).Click
Reporter.ReportEvent micWarning, “Res”, “Up to “& OrderNumer-1 &” Orders only Exist”
Exit Do
End If
OrderNumer= OrderNumer + 1
Loop

iv) Using Option Explicit Statement

Option Explicit – It forces declaration of all variables in a Script, so that we avoid miss-spell problem.
Example:

Option Explicit
Dim Tickets, Price, Total
Tickets = 8
Price = 100
Total = Tickets * Priee
Msgbox Total

V) Using “ON Error Resume Next” statement

If any Error is there, don’t stop the Script execution, skip the error and continue.

> When to Choose:

If there is no impact on final output then we can use it.

Ex:

On Error Resume Next
VbWindow(“Form1”).Activate
VbWindow(“Form1”).VbComboBox(“Combo1”).Select “Chennai”
VbWindow(“Form1”).VbComboBox(“Combo1”).Select “Goa”
VbWindow(“Form1”).VbComboBox(“Combo1”).Select “Hyderabad”
VbWindow(“Form1”).VbComboBox(“Combo1”).Select “New Delhi”
VbWindow(“Form1”).VbComboBox(“Combo1”).Select “Mumbai”

> When Not to Choose:

If any impact on final output then don’t use it.

‘On Error Resume Next
Dim a, b
a = 100
b – 50
Msgbox a+b

Debugging Scripts

i) What is Debugging?

Locating and isolating Errors through Step by Step execution is called Debugging.

Note: Debugging Scripts is Optional.

ii) When Debugging is Required?

Scenario 1:

Script is not showing errors and providing correct Output – Debugging is not required.

Scenario 2:

Script is showing errors- Debugging is optional

Note: First correct the errors then most of time we can get correct output, otherwise
we can debug the script.

Scenario 3:
Script is not showing errors and not providing correct Output – Debugging is required.
—————————–
Whenever Script is not showing any errors and not providing correct output then
Debugging is required.

iii) How to Debug Scripts?

Using VBScript debug commands and breakpoints we can debug scripts.

Important Debug Commands:

a) Step Into (F11)
1) It starts the Script Execution.
2) It executes one statement at a time.
3) If is function call, opens the function and executes one function statement at a time.

b) Step Over (F10)
1) It executes one statement at a time.
2) If it is function call, it executes all function statements at a time.

Note: Once we open the function using “Step Into” command then “Step Over” executes
one statement(function) at a time only.

c) Step Out (Shift + F11)
1) It executes all remaining function statements at a Time.

——————
Breakpoints (F9)

To pause the Script execution.

It is for Hybrid execution.

Script Execution:

a) At a Time execution (UFT Run Command)

b) Step by Execution (VBScript debug commands)

c) Hybrid Execution (Using UFT Run command, VBScript Debug commands and Breakpoins)

Note: Debug commands and Breakpoint available in “Run” menu (UFT tool).
——————————-
Example:

Dim a, b, c
a = 10
b = 20
c = a+b
a = 5
b = 7
c = a*b
Call Login(“gcreddy”, “mercury”)
a = 20
b = 3
c = a^b
a = 5
b = 7
c = a-b
a =100
———————————–
Debugging scripts,

Follow me on social media:

In VBScript Error Handling is mechanism to handle unwanted exceptions that might break the execution of code leading to failure of the script. So, exception handling plays a very crucial role in writing a robust scripts so that if any error occurs at runtime, the programme keeps executing the next steps even after the occurrence of errors.

VBScript Error Handling Error Handling in uft

If you are writing automation scripts in UFT, you must handle exceptions appropriately so that the Test Suite that is usually executed at daily nightly batch in unattended mode don’t get stuck due to any runtime exception.

Types of Errors in Programming

Before understanding the concept of error handling, first of all you must know what are the types error in a programming language.

There are three types of errors in any programming language.

  • Syntax Errors
  • Runtime Errors
  • Logical Errors

Syntax errors

Syntax errors cause parsing errors and are caught before VBScript code execution. A few examples of syntax errors are incorrect function names, unbalanced strings (like missing an opening or closing parenthesis, missing double quotes) and etc.

Example: The following code causes syntax error due to missing double quotes while assigning value to myVar.

Dim myVar

myVar = «MySkillPoint    ‘ Cause a syntax error as it has missing double quote

Runtime Errors

Runtime errors arise only during execution and are not detectable during code parsing. This is why they are also known as exceptions.

Example: The following code is perfectly fine and has no syntax errors. However, because we can’t divide an integer by 0, we’ll get a runtime error during execution, and the code will crash.

Dim myVar, i

i = 25

myVar = i / 0 ‘will cause runtime error

Msgbox «Division Result is: « & myVar

Runtime-Error-VBScript-UFT

Logical Errors

Logical errors means, you have written a code but you are not getting the expected outcome. In such situation you have to debug your code where you are making a mistake.

Also, Check How to Debug a Test in UFT

VBScript Error Handling Techniques

We will see how to use the following methods to catch exceptions /  errors in VBScript at runtime.

  • On Error Resume Next
  • Err Object
  • On Error GoTo 0

On Error Resume Next

The name of this method is self-explanatory: if an error occurs, resume the flow of execution to the next line of the script.

Example: We will again divide a number by 0. However, this time, the code will crash and proceed to next line and display the outcome in the message box.

Dim myVar, i

On Error Resume Next ‘Using Error handling Statement

i = 25

myVar = i / 0

MsgBox «Division Result is: « & myVar ‘ Value of myVar will not be displayed in message box owing to error divisible by 0

On error resume next vbscript uft

Err Object

This technique is most commonly used to retrieve the Error’s details so that you can write your logical code based on it if you know well in advance that an exception might occur at a particular step.

Err.NumberReturns the Error Number
Err.Description ‘ Returns the Error Description
Err.Clear ‘ Clears the Error

Example: The following example shows how to use Err object.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Dim myVar, i

On Error Resume Next ‘Using Error handling statement

i = 25

myVar = i / 0

If Err.Number <> 0 Then ‘ If an Error Occurs

    MsgBox «Error Number is: « & Err.Number & » and its Description is: « & Err.Description

    Err.Clear ‘(It will Clear the Error)

End If

On Error GoTo 0 ‘ Disabling Error Handler

On Error GoTo 0

This statement does not handle error instead it is used to disable any error handler in the script. This will set the handler to null value or Nothing, indicating that the script will no longer support error handlers. The same has been shown in the above example.

Conclusion

I hope you’ve gained a good knowledge of Error Handling in VBScript from this tutorial. If you liked this content, please share it with your friends.

Recommended Posts

  • Array in VBA UFT Excel
  • VBA Date Functions in UFT | Excel
  • Most Useful VBScript Functions That You Must Know
  • VBScript MySQL Database Connection in UFT
  • VBScript Loops: Do Loop, For Loop, For Each, and While Loop
  • How to Load Function Library at Runtime in UFT

Понравилась статья? Поделить с друзьями:
  • Обработка ошибок try catch php
  • Обратное распространение ошибки habr
  • Обработка ошибок sqlite python
  • Обрезка яблони ошибки
  • Обработка ошибок request python