Jump to content

Try...Catch Block


kin
 Share

Recommended Posts

hello All, this question maybe stupid but i did not found decision. Is there in AutoIT script analog of try...catch block or On Error Goto ... to catch the AutoIT error

10x in advance

You use the @error keyword. Like;

If @error Then
do your error stuff
else
do your program stuff
Endif
Link to comment
Share on other sites

but i mus do this on every row on my script which is not small. I ask for some general decision, for now i start another AutoIT program which wait for AutoIT Error MessageBox, but i prefer analog of try... catch block if exist in AutoIT

Link to comment
Share on other sites

but i mus do this on every row on my script which is not small. I ask for some general decision, for now i start another AutoIT program which wait for AutoIT Error MessageBox, but i prefer analog of try... catch block if exist in AutoIT

That specific coding construct does not exist in AutoIt.

You could put it in a While loop I think though:

While Not @error; Try
   ; your main logic
   ;
   ;
WEnd
If @error Then; Catch
   ; your error logic
   ;
   ;
EndIf

Dale

Free Internet Tools: DebugBar, AutoIt IE Builder, HTTP UDF, MODIV2, IE Developer Toolbar, IEDocMon, Fiddler, HTML Validator, WGet, curl

MSDN docs: InternetExplorer Object, Document Object, Overviews and Tutorials, DHTML Objects, DHTML Events, WinHttpRequest, XmlHttpRequest, Cross-Frame Scripting, Office object model

Automate input type=file (Related)

Alternative to _IECreateEmbedded? better: _IECreatePseudoEmbedded  Better Better?

IE.au3 issues with Vista - Workarounds

SciTe Debug mode - it's magic: #AutoIt3Wrapper_run_debug_mode=Y

Doesn't work needs to be ripped out of the troubleshooting lexicon. It means that what you tried did not produce the results you expected. It begs the questions 1) what did you try?, 2) what did you expect? and 3) what happened instead?

Reproducer: a small (the smallest?) piece of stand-alone code that demonstrates your trouble

Link to comment
Share on other sites

Or do an @error function like;

$ret=Run($str, $wd)
If @error then catchIt($ret)
do more stuff
Etc.

Func catchIt($er)
Handle your errors
return, exit, whatever
EndFunc

Now you just put in

If @error then catchIt($ret)

anywhere you want to catch an error.

Link to comment
Share on other sites

but i mus do this on every row on my script which is not small. I ask for some general decision, for now i start another AutoIT program which wait for AutoIT Error MessageBox, but i prefer analog of try... catch block if exist in AutoIT

sorry i just don't understand...a try/catch will only catch one error regardless of how many lines of code are within it. So you wouldn't be saving any steps even if what you're looking for existed, because you'd still have to Try...Catch every line that could raise an exception. you could do an adlib function that just watches the @error, but the thing is, you're not going to want the same action performed on every @error, example, you don't want the same code executed if a file couldn't be opened as if a color you searched for with pixelsearch() wasn't found. so what you do, is assign your function calls to variables, so that you can evaluate the return value and respond accordingly. It's much less code to handle errors as they occur than to have a try/catch for everything that COULD error.

$file = FileOpen("C:\test.txt",0)
If $file = -1 then 
MsgBox(0,"Error","File could not be opened for reading")
Exit
EndIf
$Search = PixelSearch(0,0,100,100,0xFFFFFF)
If @error then MsgBox(0,"Error","Color not found")
Link to comment
Share on other sites

I would also love to see a Try..Catch feature/function, similar to that in .Net:

Try
   [ tryStatements ]
[ Catch [ exception [ As type ] ] [ When exp[b][/b]ression ] 
   [ catchStatements ] ]
[ Exit Try ]
...
[ Finally
   [ finallyStatements ] ]
End Try

“Give a man a script; you have helped him for today. Teach a man to script; and you will not have to hear him whine for help.”AutoIt4UE - Custom AutoIt toolbar and wordfile for UltraEdit/UEStudio users.AutoIt Graphical Debugger - A graphical debugger for AutoIt.SimMetrics COM Wrapper - Calculate string similarity.

Link to comment
Share on other sites

sorry i just don't understand...a try/catch will only catch one error regardless of how many lines of code are within it. So you wouldn't be saving any steps even if what you're looking for existed, because you'd still have to Try...Catch every line that could raise an exception. you could do an adlib function that just watches the @error, but the thing is, you're not going to want the same action performed on every @error, example, you don't want the same code executed if a file couldn't be opened as if a color you searched for with pixelsearch() wasn't found. so what you do, is assign your function calls to variables, so that you can evaluate the return value and respond accordingly. It's much less code to handle errors as they occur than to have a try/catch for everything that COULD error.

$file = FileOpen("C:\test.txt",0)
If $file = -1 then 
MsgBox(0,"Error","File could not be opened for reading")
Exit
EndIf
$Search = PixelSearch(0,0,100,100,0xFFFFFF)
If @error then MsgBox(0,"Error","Color not found")
That is why you always pass a variable with an @error function.

$ret=Run($str, $wd)
If @error then catchIt($ret)
do more stuff
$ret=Run($str, $wd)
If @error then catchIt("!Failed to run " & $str & ". From working directory " $ $wd)
Etc.

Func catchIt($er)
Select
  Case $er=1
     MsgBox(0, "Unknown Error", "Exiting")
     Exit
 Case StringLeft($er, 1)="!"
     MsgBox(0, "Error", $er)
 Case
Etc, etc
EndFunc

With the variable passed to catchIt($) you can impart any information generic, general, or with simple tricks very specific to use to populate the info strings in a message bog, determine wether the app should be closed or not, etc etc...


            
        

        

        
    

    

    




    Link to comment
    
        
    
    
    

    
    Share on other sites
    

    
        
            

    

        
            

    

        
            

    

        
            

    

        
    


    
    More sharing options...

    


    

                    
                    
                    
                

                    

                    
                    





    

    

    
        
            
                


    
        
    

                
                
                    
                        

                    
                
            
        
        
            
                


seandisanti
            
            
                Posted 
                
            
        
    
    
        


seandisanti
            
        
        
            
                
                    


    
        
    

                    
                    
                        

                    
                
            
            
                Active Members
                
            
            
                
                    
                        
                            
                                
                            
                                 2.9k
                            
                                
                            
                        
                        
                    
                
            
            
                

            
        
    
    
        



    
        
            
                
                    
                    
                    
                    
                    
                
            
            
                
                    
                    
                        
                        
                            Share
                        
                        
                        
                        
                        
                            
                                
                            
                            
                            
                            
                            
                            
                        
                    
                
                
            
        

        
            Posted 
            
            
                
                
            
        
    

    

    

    
        
        
            That is why you always pass a variable with an @error function.

 

$ret=Run($str, $wd)

If @error then catchIt($ret)

do more stuff

$ret=Run($str, $wd)

If @error then catchIt("!Failed to run " & $str & ". From working directory " $ $wd)

Etc.

Func catchIt($er)

Select

Case $er=1

MsgBox(0, "Unknown Error", "Exiting")

Exit

Case StringLeft($er, 1)="!"

MsgBox(0, "Error", $er)

Case

Etc, etc

EndFunc

With the variable passed to catchIt($) you can impart any information generic, general, or with simple tricks very specific to use to populate the info strings in a message bog, determine wether the app should be closed or not, etc etc...

exactly, that was my point, that the way things are currently handled works very well when used correctly, and IMHO implementation of a Try...Catch structure would be considered unnecessary at best. It would require more code to achieve the same result. Try...Catch structures are to prevent crashes caused by unhandled exceptions. It's actually going on in the background with Autoit, when you try to open a file for example, if there is an error, or the operation is unsuccessful for whatever reason, autoit catches the exception, and lets you know by setting @error. I could be completely wrong on this, but i believe that in order to actually allow true Try/Catch, they'd have to make an Opt() to pass exceptions to the script, rather than having it handled by autoit3.exe, and that would probably require additional code in functions that could cause an exception so that it's executed differently depending on how that option is set
Link to comment
Share on other sites

That specific coding construct does not exist in AutoIt.

You could put it in a While loop I think though:

While Not @error; Try
  ; your main logic
  ;
  ;
WEnd
If @error Then; Catch
  ; your error logic
  ;
  ;
EndIf

Dale

Wouldnt this code reset the @error macro everytime it was brought around so it would never be the right one?

If I am not mistaken... the @error macro is reset with each new function call. I dont know if that includes the While...WEnd as it isnt a function.

Just my thoughts,

JS

AutoIt Links

File-String Hash Plugin Updated! 04-02-2008 Plugins have been discontinued. I just found out.

ComputerGetInfo UDF's Updated! 11-23-2006

External Links

Vortex Revolutions Engineer / Inventor (Web, Desktop, and Mobile Applications, Hardware Gizmos, Consulting, and more)

Link to comment
Share on other sites

Wouldnt this code reset the @error macro everytime it was brought around so it would never be the right one?

If I am not mistaken... the @error macro is reset with each new function call. I dont know if that includes the While...WEnd as it isnt a function.

Just my thoughts,

JS

yes, that's kind of what i was trying to say about it not saving any time to use a try/catch if it magically became available, because you'd have to add atleast 2 lines of code for every line of your code that could set the @error.
Link to comment
Share on other sites

The idea is to replace:

Func MyFunc()
   SomeFuncA()
   if @error <> 0 then
      msgbox(1,"Error", "Some error")
   endif
   SomeFuncB()
   if @error <> 0 then
      msgbox(1,"Error", "Some error")
   endif
   SomeFuncC()
   if @error <> 0 then
      msgbox(1,"Error", "Some error")
   endif
   SomeFuncD()
   if @error <> 0 then
      msgbox(1,"Error", "Some error")
   endif
End Func

where it is hard to see what the code is doing for all the debug code, with:

Func MyFunc()
   Try
      SomeFuncA()
      SomeFuncB()
      SomeFuncC()
      SomeFuncD()
   Catch @error
      msgbox(1,"Error", "Some error")
   Finally
      CleanUpFunc()
   End Try
End Func

Which is easier to read.

Behind the scenes, AutoIt would have to monitor the @error returned by each function and jump to the Catch line if it is not zero. Of course there would be no way to know which function caused the error, unless unique error codes are used for each function. On a related note, the addition of an @ErrorMsg macro generated by a function would be good to get around this in that the message could contain more explicit details, including the function name. Similar to err.number and err.description in VB.

Another problem, as identified by cameronsdad is unhandled exceptions. I don't think that there is any way for the code to catch these. My original post was generated because of some COM object code that I was working on, which could generate errors all over the place if the control does not act correctly. There was alot of complicated code, with very little error handling.

“Give a man a script; you have helped him for today. Teach a man to script; and you will not have to hear him whine for help.”AutoIt4UE - Custom AutoIt toolbar and wordfile for UltraEdit/UEStudio users.AutoIt Graphical Debugger - A graphical debugger for AutoIt.SimMetrics COM Wrapper - Calculate string similarity.

Link to comment
Share on other sites

Behind the scenes, AutoIt would have to monitor the @error returned by each function and jump to the Catch line if it is not zero. Of course there would be no way to know which function caused the error, unless unique error codes are used for each function. On a related note, the addition of an @ErrorMsg macro generated by a function would be good to get around this in that the message could contain more explicit details, including the function name. Similar to err.number and err.description in VB.

Another problem, as identified by cameronsdad is unhandled exceptions. I don't think that there is any way for the code to catch these. My original post was generated because of some COM object code that I was working on, which could generate errors all over the place if the control does not act correctly. There was alot of complicated code, with very little error handling.

the thing is, you're not going to have per line error trapping without per line error handling. right now there is the ability to handle errors with a single line usually, where try/catch by it's nature implies atleast 2 addition lines of error trapping, per possible exception thrown. as far as @errormsg macro, we have @error, which can be set to any integer by any function. most of the built in functions that could fail for a variety of reasons have different possible error returns to indicate what exactly the problem is, and any function you create you could throw in your own error with seterror() or even elaborate on that more with setextended(). in any event, if you call 3 functions, and there are 3 different possibilities for errors, you will have to have code to handle 3 different errors. I'm now saying the same things over and over, so i'll try to leave it at that...
Link to comment
Share on other sites

Wouldnt this code reset the @error macro everytime it was brought around so it would never be the right one?

If I am not mistaken... the @error macro is reset with each new function call. I dont know if that includes the While...WEnd as it isnt a function.

Just my thoughts,

JS

Yep, you're right based on a quick test. It seemed logical at the time. From the helpfile:

Remarks

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.

Dale

Free Internet Tools: DebugBar, AutoIt IE Builder, HTTP UDF, MODIV2, IE Developer Toolbar, IEDocMon, Fiddler, HTML Validator, WGet, curl

MSDN docs: InternetExplorer Object, Document Object, Overviews and Tutorials, DHTML Objects, DHTML Events, WinHttpRequest, XmlHttpRequest, Cross-Frame Scripting, Office object model

Automate input type=file (Related)

Alternative to _IECreateEmbedded? better: _IECreatePseudoEmbedded  Better Better?

IE.au3 issues with Vista - Workarounds

SciTe Debug mode - it's magic: #AutoIt3Wrapper_run_debug_mode=Y

Doesn't work needs to be ripped out of the troubleshooting lexicon. It means that what you tried did not produce the results you expected. It begs the questions 1) what did you try?, 2) what did you expect? and 3) what happened instead?

Reproducer: a small (the smallest?) piece of stand-alone code that demonstrates your trouble

Link to comment
Share on other sites

Yep, you're right based on a quick test. It seemed logical at the time. From the helpfile:

Dale

Yea it does still seem logical, but like your quote showed... it isnt.

I am glad you looked it up. I forgot to. :lmao:

JS

AutoIt Links

File-String Hash Plugin Updated! 04-02-2008 Plugins have been discontinued. I just found out.

ComputerGetInfo UDF's Updated! 11-23-2006

External Links

Vortex Revolutions Engineer / Inventor (Web, Desktop, and Mobile Applications, Hardware Gizmos, Consulting, and more)

Link to comment
Share on other sites

  • 17 years later...

Here is my goofy workaround for a try catch type block:
And yes I know this thread is ancient...but it is the first google search result for me for autoit try catch so I though others searching might find it useful.

Global $_TRY = False
Global $_CATCH = False

func myfunc1()
    If $_TRY And $_CATCH Then Return SetError(1)

    ConsoleWrite('run func1 stuff here...' & @CRLF)

    Local $error_condition = True

    If $error_condition Then
        SetError(1)
        If $_TRY Then $_CATCH = True
    EndIf
EndFunc

func myfunc2()
    If $_TRY And $_CATCH Then Return SetError(1)

    ConsoleWrite('run func2 stuff here...' & @CRLF)

    Local $error_condition = False

    If $error_condition Then
        SetError(1)
        If $_TRY Then $_CATCH = True
    EndIf
EndFunc


$_TRY = True ; try block start
    myfunc1()
    myfunc2()
$_TRY = False ; try block end
; catch
If $_CATCH Then
    ConsoleWrite('handle error' & @CRLF)
EndIf
$_CATCH = False ; reset flag for use in next try-catch block

Output:
 

run func1 stuff here...
handle error

I am sure someone could improve upon this.

Edited by garbb
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...