Exceptions

Exceptions and errors are strongly correlated, but they are different things. An exception, for example, can be gracefully handled. Here are some examples of exceptions:

0/0 

Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero

len(1, 2)

Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: len() takes exactly one argument (2 given)

pi * 2

Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'pi' is not defined

In this example, three different exceptions have been raised (see the last line of each block). To handle exceptions, you can use a try...except block in the following way:

try: 
a = 10/0
except ZeroDivisionError:
a = 0

You can use more than one except clause to handle more than one exception. You can eventually use a final all-the-other exception case handle. In this case, the structure is as follows:

try: 
<code which can raise more than one exception>
except KeyError:
print ("There is a KeyError error in the code")
except (TypeError, ZeroDivisionError):
print ("There is a TypeError or a ZeroDivisionError error in the code") except:
print ("There is another error in the code")

Finally, it is important to mention that there is the final clause, finally, that will be executed in all circumstances. It's very handy if you want to clean up the code (closing files, de-allocating resources, and so on). These are the things that should be done independently, regardless of whether an error has occurred or not. In this case, the code assumes the following shape:

try: 
<code that can raise exceptions>
except:
<eventually more handlers for different exceptions>
finally:
<clean-up code>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset