Jump to content

@error when is the right time to use it ?


Recommended Posts

i was chatting to storme the other day and he advised i should use @error more in my scripts.

I tend to use consolwrite to check things and when im happy with a piece of code i remove them which i gather from him is not the way to do it.

So to the question..

When do i use it correctly

Just after a major thing like an InetGet for eg or calling a udf?

Or

Should i be using them on every time an action happens?

And how do i get it to give the right info so i can troubleshoot?

So would any of these need it adding?

Case FileExists($FF32_path)
    If $Internet = 1 Then
    $FF_check_key = _GetUpdates("Firefox")
    IniWrite(@ScriptDir & "\file_includes\config.ini", "Firefox", "Current Version ", $FF_check_key)
    Else
    $FF_check_key = IniRead(@ScriptDir & "\file_includes\config.ini", "Firefox", "Current Version", "Not Found")
    EndIf

Or

$CBoxStatFF = GUICtrlRead($CBoxFF)
    If $CBoxStatFF = $GUI_CHECKED Then
    SplashTextOn(" Installing ", " Firefox Is Being Installed ", 250, 50, -1, -1, 0, "Tahoma", 10, 600)
    ShellExecuteWait(@ScriptDir & '\file_includes\install_firefox.exe', IniRead(@ScriptDir & "\file_includes\updates.ini", "Firefox", "Switch_0", "Not Found"))
    Sleep(1500)
    SplashOff()
    EndIf
    Sleep(500)

Or

InetGet('http://www.piriform.com/defraggler/', @ScriptDir & "\file_includes\install_defraggler.exe", 1, 1)

Or

$DFG_down_key = _GetUpdates("Defraggler")
    IniWrite(@ScriptDir & "\file_includes\config.ini", "Defraggler", "Download Version ", $DFG_down_key)

These are just examples of things in one of my scripts

So a little advise on correct usage would be cool

Link to comment
Share on other sites

I suppose it depends on who is using the script, what its for and so forth.

It seems you tend to think of it as a debugging aid, but its much more than that.

If you intend to distribute your script then the more potential errors that are dealt with, the more robust your script will be.

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Link to comment
Share on other sites

I suppose it depends on who is using the script, what its for and so forth.

It seems you tend to think of it as a debugging aid, but its much more than that.

If you intend to distribute your script then the more potential errors that are dealt with, the more robust your script will be.

Yes i want to distribute this one.

I dont really know how to think of it as i never use it.

Link to comment
Share on other sites

  • Moderators

Chimaera,

a little advise on correct usage

You would probably get a different answer from everyone here - so I have no idea what you would consider "correct"! :blink:

My take: My main uses for @error:

1. To catch the error which is going to crash the script because something has not gone as expected. An example would be if the code was expecting to get an array returned and then use the elements - what if the array was not returned? Here are a couple of examples from one of my scripts:

Looking for the SysTray:

$aPos = ControlGetPos("[Class:Shell_TrayWnd]", "", "[Class:ToolbarWindow32;Instance:1]")
If @error Then Return
; Continue icon position calculation
$iIcon_X += $aPos[0]
$iIcon_Y += $aPos[1]

If for some reason the SysTray is not found for any reason the whole process is aborted rather then AutoIt throwing its hands up and giving an "Index used on a non-array variable" error (or whatever it does say :)).

Expecting an array, but might not get one:

; Fill track index array
$aTrack_Index = _RecFileListToArray($sMusic_Folder, "*.mp3;*.wma;*.wav", 1, 1, 1)
If @error Then
    ; Set empty array to indicate failed load
    Global $aTrack_Index[1] = [0]
    [...]
EndIf

This is the sort of basic errorchecking code which should be added to any script that you want to run smoothly - or expect anyone else to use. :)

2. As a convenient way to split a conditional. I tend to use code like this after functions like _ArraySearch:

$iIndex = _ArraySearch($aVertex, $aLines[$i], 1)
If @error Then
    ; Not found
    [...]
Else
    ; Found
    [...]
EndIf

You could use If $iIndex = -1 as well, but If @error is shorter. But if you do this, beware putting a ConsoleWrite to check what value of $iIndex is returned - you will never get the @error set if you do. :party:

This is for your convenience rather than errorchecking purposes.

3. When you need to identify the particular error that occurred. Several of the native functions and many of the UDFS return different @error values depending on the problem encountered and you may want to take different actions depending on the problem. Taking _ArraySearch as an example, imagine you were asking the user to set start and finish values for the search - unless you coded a check on these values yourself you might well get an @error value of 4 ($iStart is greater than $iEnd) as well as 6 ($vValue was not found in array) and would need to distinguish between them before deciding what action to take next - like this:

$iIndex = _ArraySearch($aVertex, $aLines[$i], 1)
If @error Then
    Switch @error
        Case 4
            ; Start > End
            [...]
        Case 6
            ; Not found
            [...]
    EndSwitch
Else
    ; Found
    [...]
EndIf

Some food for thought I hope. :)

M23

Edit:

Incorrect code removed - see below for details if you really must! :mellow:

Edited by Melba23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

I suppose it depends on who is using the script, what its for and so forth.

It seems you tend to think of it as a debugging aid, but its much more than that.

If you intend to distribute your script then the more potential errors that are dealt with, the more robust your script will be.

I agree!

With @error you can catch errors such as

- No Internet

- corrupt downloads

- missing program/installer/support file

- etc

You can then

- Bring up and error

- Try again without informing the user

- try a alternative approach

@error is particularly important after commands that may break your script if they fail.

EG You have a download that is needed for the next step

Lesser things like.... Hmm changing the background colour of the screen for effect.... then @error is optional.

The only thing to keep an eye on is if you have tight loops.

IF you NEED it to run FAST and you are SURE that no errors are going to occure then don't use the @error.

OR

Do some prechecks before the loop to check that nothing will go wrong in the look.

N E Way hope that clarifies things (as I see them then :mellow:)

Have fun!

John Morrison

Link to comment
Share on other sites

Chimaera,

You would probably get a different answer from everyone here - so I have no idea what you would consider "correct"! :mellow:

M23

Thats about what i expected M23

Thats helpfull thanks, i have a couple of questions about how it returns if i may

If @error Then Return

Does this give the error you see sometimes that gives the line number and some autoit stuff after it [i dont know what the error is called]

If @error Then
    ; Not found
    [...]
Else
    ; Found
    [...]
EndIf

And this one i assume is the one i can specify what i want rather than the error itself with a MsgBox?, because the error is not important just the happening of it?

Thanks for the other examples although i try my hardest to not use arrays so they will be for another time.

Link to comment
Share on other sites

...

3. When you need to identify the particular error that occurred. Several of the native functions and many of the UDFS return different @error values depending on the problem encountered and you may want to take different actions depending on the problem. Taking _ArraySearch as an example, imagine you were asking the user to set start and finish values for the search - unless you coded a check on these values your self you might well get an @error value of 4 ($iStart is greater than $iEnd) as well as 6 ($vValue was not found in array) and would need to distinguish between them before deciding what action to take next. But beware, you can only use the @error variable once - this will not work:

$iIndex = _ArraySearch($aVertex, $aLines[$i], 1)
If @error Then
    Switch @error
        Case 4
            ; Start > End
            [...]
        Case 6
            ; Not found
            [...]
    EndSwitch
Else
    ; Found
    [...]
EndIf

You need to do this:

$iIndex = _ArraySearch($aVertex, $aLines[$i], 1)
Switch @error
        Case 0
            ; Found
            [...]
        Case 4
            ; Start > End
            [...]
        Case 6
            ; Not found
            [...]
EndSwitch

Or save the @error return into a variable for later use:

; Determine GUI client area
DllCall("user32.dll", "bool", "GetClientRect", "hwnd", $hAperture, "ptr", DllStructGetPtr($tRect))
Local $iError = @error
If $iError Then Return SetError($iError, @extended, -3)
Don't want to nitpick, but ... :mellow:

You can use the @error macro as often as you like ... until it is changed by another function.

The first of the above examples works just fine, so there's no need for example two.

Example 3 isn't necessary - you can use:

; Determine GUI client area 
DllCall("user32.dll", "bool", "GetClientRect", "hwnd", $hAperture, "ptr", DllStructGetPtr($tRect))
If @error Then Return SetError(@error, @extended, -3)
I do it all the time in my AD and OutlookEX UDF. Edited by water

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2022-02-19 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (NEW 2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

Kinda mystified.

Problem with @error and native autoit functions is that not all functions use/have it.

@error value is also reset on a new function call. For both native and user function. (for user functions @error can be maintained if needed of course).

The question 'When, or when not, to use @error as error flag in your user functions' seems more logical to me.

Which I think is also kinda personal, unless you have no choice of course.

"Straight_and_Crooked_Thinking" : A "classic guide to ferreting out untruths, half-truths, and other distortions of facts in political and social discussions."
"The Secrets of Quantum Physics" : New and excellent 2 part documentary on Quantum Physics by Jim Al-Khalili. (Dec 2014)

"Believing what you know ain't so" ...

Knock Knock ...
 

Link to comment
Share on other sites

  • Moderators

water,

Don't want to nitpick

But you are quite right to do so. :mellow:

That is my learning point for today - I wonder where I got that mistaken idea from? :)

Thanks for pointing it out - ealrier post amended. :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Melba,

I once learned it the hard way myself when debugging a script.

A function returned an error and to make sure the error handling routine worked correctly I put a ConsoleWrite after the function call. Something like:

$iReturnValue = FunctionCall()
ConsoleWrite($iReturnValue & " - " & @error @CRLF)
If @error Then 
   ; Error handling code
EndIf
The error handling routine never got triggered. It took me a few minutes to realize that ConsoleWrite sets @error as well :mellow:

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2022-02-19 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (NEW 2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

  • Moderators

water,

I can only imagine that I must have mis-learnt that it was necessary to save the @error return value by doing something similar when I first started using AutoIt. :mellow:

Again thanks for pointing out the error - now to search my scripts for unneccesary $iError variables! :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

That is my learning point for today - I wonder where I got that mistaken idea from? :mellow:

Thanks for pointing it out - ealrier post amended. :)

M23

I had the same idea (that is was destroyed)...

From the help file for "SetError"

When entering a function @error is set to 0. Unless SetError() is called, then @error will remain 0 after the function has ended. This means that in order for @error to be set after a function, it must be explicitly set. This also means you may need to backup the status of @error in a variable if you are testing it in a While-WEnd loop.

So it looks like everyone is right. It doesn't get reset UNLESS.. you enter a function.... :)

Storm-E

Link to comment
Share on other sites

;; that's after the function parameter are processed. ... very handy.
func myfuncion(data_parm1, data_parm2, etc, $parent_Error_Value = @error)
    ;; just remember that calling a function that is maintaining the @error value,
    ;; will not maintain the passing of that @error value back to the parent/caller.
    setError($parent_Error_Value)
    OtherFunctionThatMaintainsThe@errorValue()
    ;; will now pass zero instead of the currently set @error value to the caller (of this function).
    return
endfunc

"Straight_and_Crooked_Thinking" : A "classic guide to ferreting out untruths, half-truths, and other distortions of facts in political and social discussions."
"The Secrets of Quantum Physics" : New and excellent 2 part documentary on Quantum Physics by Jim Al-Khalili. (Dec 2014)

"Believing what you know ain't so" ...

Knock Knock ...
 

Link to comment
Share on other sites

This seems to have got a little off track from where we started, could anyone just clarify this for me

I have a couple of questions about how it returns if i may

If @error Then Return

Does this give the error you see sometimes that gives the line number and some autoit stuff after it [i dont know what the error is called]

If @error Then
    ; Not found
    [...]
Else
    ; Found
    [...]
EndIf

And this one i assume is the one i can specify what i want rather than the error itself with a MsgBox?, because the error is not important just the happening of it?

Link to comment
Share on other sites

This seems to have got a little off track from where we started, could anyone just clarify this for me

All @error gives you is the error code returned from the previous function.

The linenumber and "other stuff" you have to put together yourself if you want to display/log that info.

If @error Then Return

Will just "return" from the function if the @error value isn't 0...

NO message will be displayed

Hpe that clarifies :mellow:

John Morrison

Link to comment
Share on other sites

AutoIt returns " ... gives the line number and some autoit stuff ..." only when an error occurres that AutoIt can not handle.

This can be a syntax error when the syntax check is done before executing the script or during runtime when a severe error occurred (e.g. accessing element 11 when the array just has 10)

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2022-02-19 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (NEW 2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...