Tuesday, May 17, 2011

Error handling in QTP using On Error

By using QTP recovery scenario, we can handle errors.

The other way around handling Errors is using "On Error" statements.

Following code throws an Exception at Line 6, and the execution cannot proceed further.
msgbox "hello"
call funcOne
msgbox "after function call"

function funcOne()
msgbox 1/0
end function
Here the output is "hello", the script never reaches to the second output statement

To proceed further after the exception occured, use "On Error Resume Next" statement, which just ignores the Exception and proceeds.
msgbox "hello"
call funcOne
msgbox "after function call"

function funcOne()
On Error Resume Next
msgbox 1/0
end function
Here the output contains both the messages

To customize the error message displayed, use the Err Object
msgbox "hello"
call funcOne
msgbox "after function call"

function funcOne()
On Error Resume Next
msgbox 1/0
msgbox "Error Message: "&Err.Description&" and Error code: "&Err.Number
end function
Here the output is 3 msgs, including the Error description.

To disable Error Handling mechanism use "On Error Goto 0" statement.
msgbox "hello"
call funcOne
msgbox "after function call"

On Error Goto 0

call funTwo ' here the Error occues as we disabled Error Handling

function funcOne()
On Error Resume Next
msgbox 1/0
msgbox "Error Message: "&Err.Description&" and Error code: "&Err.Number
end function

You can also clear the Error object using Err.clear().

No comments: