Friday, June 24, 2022

Sikulix Exception

I've been experimenting with Ubuntu on a dynabook N40 with sikulix, and I've made a lot of stupid mistakes right away (LoL). Well, that's how programmers gain experience. Yesterday, I made a mistake in handling "except".

#
def log_print(m): # debug print
    print(m) # print message.
#
print(App.openLink("https://google.com")) # open google.com in standard browser
try:
    wait("image.png",15) # wait 15 seconds at the longest until image.png is found
    log_prinh("Found.")
except: # if not found for 15 seconds, jump to here
    log_print("Not found.")
#
click() # without argument, left-click on the last match.

When you look at this source, then if aware "This is no good!", you have excellent taste! (LOL). Actually, it was running fine until halfway through and then suddenly stopped working (;-o). No matter how I tried, the images no longer matched. I took screenshots again and again, changed similar rate, and so on, but nothing worked. I thought it was a bug in sikulix. (That can't be it!))   Then, about half a day later, I somehow start feeling :

  • "except:" might be catching other exceptions than no image found??!!

I noticed that. I looked at the source carefully, and found that somehow, strange characters were mixed in with the functions I had defined (;-o). I was not sure why, but I found out that I had rewritten a function that I had not defined. Since python is a scripting language, so if I wrote a function that I had not defined, it would not give me a compile error, but would be handled as an exception at runtime, so the error message was absorbed by the exception and no longer appeared.
I almost blame python, but when I think about it, I remember that I have been doing the same thing in java for a long time, write all the exceptions into one except, and getting into trouble later. I haven't progressed at all. 。。。。 Of course, usually they code like this:

try:
    wait("image.png",15) # wait 15 seconds at the longest until image.png is found
    log_prinh("Found.")
except FindFailed: # if not found in 15 seconds, jump to here
    log_print("Not found.")

This way, even if you write a strange (undefined) function, it will not be hidden by an exception, and you will notice it immediately at runtime. If you want to handle other exceptions, you can do something like this.

try:
    wait("image.png",15) # wait 15 seconds  at the longest until image.png is found
    log_prinh("Found.")
except FindFailed: # if not found in 15 seconds, jump to here
    log_print("Not found.")
except Exception as e: # Other exceptions
    print("Error happen!!!!")
    print(e)
    exit(1)

Actually code successfly jumped to the last "except", because the function was wrong (:-o). The lesson of the day is.

  • Cutting corners code takes up your time in the future.

(LOL)

Labels: , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home