If at first you don’t succeed, hide all evidence that you tried.

I always hated working with exemption handling in other languages. The end result was always cryptic, over complicated and usually unreliable. So I often ended up idiot proofing my code so as to avoid having erroneous data processed in the first place. Python’s exemption handling is different; very simple, clear and the damn thing actually works.

I’m using the PyEphem module to do all my astronomical calculations. Its a great module and its actually smart enough to barf up an error when I tried to determine a rise time for Polaris in the Northern Hemisphere. You can stop laughing now. Rather than writing ridiculously complicated code to avoid this circumstance, I simply allowed the error to occur and let Python catch it and clean it up.

 

try:
    riseCell[n].setText(str(observer.next_rising(object)).split(” “)[1][:8])
except ephem.AlwaysUpError:
    riseCell[n].setText(“Circumpolar”)
except ephem.NeverUpError:
    riseCell[n].setText(“Never Visible”)

I’m finding all sorts of uses for the Try & Except trick, like when calling an external application such as a web browser to display a HTML file. Browsers have a tendency to take a while to load unless cached. Python get a little impatient and can issue an error claiming things didn’t load.

try:
    webbrowser.open_new(url)
except WindowsError:
    pass

… and all the errors get hidden. So boys and girls, today’s lesson is if at first you don’t succeed, hide all evidence that you tried.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s