Implementing try-catch functionality in QTP/UFT

Hello friends,

In this post we will discuss about how we can generate the same try catch behavior in VBS/UFT, which comes inbuilt in Java or .Net and which is available all other automation testers.

Take a look on the below function.

Public Function ImplementTryCatch()
‘disable error handler
On Error Resume Next

‘Execute some statements gere 
c = 10 + 20

‘enable error handler
On Error Goto 0

End Function

It’s a normal function, where at the start, we are disabling the error handler and hence UFT will not through any errors, and at the end of the function we are enabling error handler so any code executed after this function call will throw errors. Now to implement a try catch structure we have to consider this function as the parent function and implement the actual child function which might throw errors.

Now take a look at the below Child function

Public Function ChildFunction()

‘Execute this for successfull execution
‘C = 1+0

‘Execute this for error function call
C = 1/0

ChildFunction = C

End Function

The above function will always through error because 1/0 cannot be evaluated. Now if we combine two functionalities here, then it will look something like this

‘This function will implement try catch functionality
Public Function ImplementTryCatch()
‘disable error handler
On Error Resume Next

‘try part
‘Execute some statements here 
Msgbox ChildFunction

‘Catch part
If Err.Number <> 0 Then
Msgbox “Error Occurred while executing child function : ” + Err.Description
End If

‘enable error handler
On Error Goto 0
End Function

Public Function ChildFunction()
‘Execute this for successful execution
‘C = 1+0
‘Execute this for error function call
C = 1/0
ChildFunction = C
End Function

Now how this whole setup works is, we have to keep the whole try (which might generate errors) functionality in separate function.

In Case of error in child function, because of the “on error resume next” statement in the parent function, child function will not be able to throw errors and also it will not be able to execute any other statements after error, because it does not have “On Error resume next” defined in it. Hence child function will return error to the parent function; parent function will not execute Msgbox statement because of the error is passed back by child function. Hence next line will be executed which will be check the error number and display error message.

One response to “Implementing try-catch functionality in QTP/UFT

  1. Pingback: Implementing CI using Jenkins and UFT | Automation Insights·

Leave a comment