Skip to main content
gamedev.net
Python #10 - Exceptions

Python #10 - Exceptions

okonomiyaki
Programmology · · 1 min read
607 2

PRO Tired of ads? Read GameDev.net ad-free and help keep the community independent with GameDev Pro — $3/month.

Exceptions in Python are handled using the standard "try/catch" statement, except Python uses "except" instead of "catch". Of course, it conforms to the syntax of Python. You can have several catch clauses with different types of exceptions. Something which I haven't seen before is the ability to add an "else" statement to the try/except block. Code in this block must executed after the "try" block if it does not raise an exception.

But why not just add code after the try/except block? That would do the same thing.
try:     x = (1,2,3)except:     print 'Error!'else:     (a,b,c) = x     print a, b, c


Ok, that works... but wouldn't this do that same thing?

try:     x = (1,2,3)except:     print 'Error!'(a,b,c) = xprint a, b, c


I don't see a point in the "else" statement.

Otherwise, here's an example of catching certain types of exceptions:
try:    f = open('myfile.txt')    s = f.readline()    i = int(s.strip())except IOError, (errno, strerror):    print "I/O error(%s): %s" % (errno, strerror)except ValueError:    print "Could not convert data to an integer."except:    print "Unexpected error!


--
Edit:

My question was answered. My mind is foggy today! Of course, the else block only executes when an exception doesn't occur. If an exception occurs, you can handle it and continue executing normally, but the else block is skipped.

I was thinking of the case where you threw the exception up, which would exit the function and there wouldn't be any use for 'else.'

Discussion

Loading comments...