Page 1 of 1

Try/Catch: how to check the error code?

Posted: 30 Jun 2020, 17:56
by john_c
Here is simple script:

Code: Select all

ImageSearch, OutputVarX, OutputVarY, X1, Y1, X2, Y2, ImageFile
If (ErrorLevel = 2)
    MsgBox % "File not found."
Else If (ErrorLevel = 1)
    MsgBox % "Image not found."
Now I'm trying to use Try/Catch instead. It doesn't work properly (it shows me "Image not found" every time). Guys, how to fix it?

Code: Select all

Try
    ImageSearch, OutputVarX, OutputVarY, X1, Y1, X2, Y2, ImageFile
Catch e
    If (e = 2)
        Throw "File not found."
    Else ; e = 1
        Throw "Image not found."

Re: Try/Catch: how to check the error code?  Topic is solved

Posted: 30 Jun 2020, 19:11
by boiler
The variable e doesn't become 2. You can act on e.message, which will be 2 for a badly formed statement. In this case, not only is it not finding the file, but the search rectangle isn't defined since the variables aren't defined. So it doesn't necessarily mean only that the file isn't found.

Another issue is that you don't want to use Throw here. Throw is what you would use to generate an error to be caught, not to display it. This is closer to what you want:

Code: Select all

Try
    ImageSearch, OutputVarX, OutputVarY, X1, Y1, X2, Y2, ImageFile
Catch e
    If (e.message = 2)
        MsgBox "File not found."
    Else
        MsgBox "Image not found."
However, another issue with that is that you're not going to get a message if you have a valid statement (good search rectangle and file name) but just can't find the file because not being able to find the file is not considered a run-time error. It's just one of the two expected outcomes of a valid search, so it won't catch anything. Try out the above code with a valid rectangle and an image file that it can find. Even if it doesn't find the image, it won't show any MsgBox.

See examples in the Try documentation.

Re: Try/Catch: how to check the error code?

Posted: 30 Jun 2020, 19:12
by swagfag
it only throws for malformed ImageSearch parameters and failed native calls
e is an exception object
e.Message contains the errorlevel(2)
e.What - the function name("ImageSearch")

ie, u still have to check ErrorLevel to see whether the image search managed to find ur image(0/1)

Re: Try/Catch: how to check the error code?

Posted: 01 Jul 2020, 03:35
by john_c
Boiler and Swagfag, thanks. Boiler, I assume you mean the image, not a file here :)
However, another issue with that is that you're not going to get a message if you have a valid statement (good search rectangle and file name) but just can't find the image because not being able to find the image is not considered a run-time error.

Re: Try/Catch: how to check the error code?

Posted: 01 Jul 2020, 04:54
by boiler
Correct. I should have said image. If the file is in place and the statement is otherwise also correct, then ErrorLevel of 0 or 1 are normal results and will not produce a catchable error.