{article Dive into Python}{title} {text} {/article}

Like many other programming languages, Python has exception handling via try...except blocks.


Python uses try...except to handle exceptions and raise to generate them. Java and C++ use try...catch
to handle exceptions, and throw to generate them.
Exceptions are everywhere in Python. Virtually every module in the standard Python library uses them, and Python
itself will raise them in a lot of different circumstances. You've already seen them repeatedly throughout this book.

  • · Accessing a non−existent dictionary key will raise a KeyError exception.
  • · Searching a list for a non−existent value will raise a ValueError exception.
  • · Calling a non−existent method will raise an AttributeError exception.
  • · Referencing a non−existent variable will raise a NameError exception.
  • · Mixing datatypes without coercion will raise a TypeError exception.

In each of these cases, you were simply playing around in the Python IDE: an error occurred, the exception was
printed (depending on your IDE, perhaps in an intentionally jarring shade of red), and that was that. This is called an
unhandled exception. When the exception was raised, there was no code to explicitly notice it and deal with it, so it
bubbled its way back to the default behavior built in to Python, which is to spit out some debugging information and
give up. In the IDE, that's no big deal, but if that happened while your actual Python program was running, the entire
program would come to a screeching halt.


An exception doesn't need result in a complete program crash, though. Exceptions, when raised, can be handled.
Sometimes an exception is really because you have a bug in your code (like accessing a variable that doesn't exist),
but many times, an exception is something you can anticipate. If you're opening a file, it might not exist. If you're
connecting to a database, it might be unavailable, or you might not have the correct security credentials to access it. If
you know a line of code may raise an exception, you should handle the exception using a try...except block.

Opening a Non−Existent File

>>> fsock = open("/notthere", "r")
Traceback (innermost last):
File "<interactive input>", line 1, in ?
IOError: [Errno 2] No such file or directory: '/notthere'

>>> try:
fsock = open("/notthere")
except IOError:
print ("The file does not exist, exiting gracefully")
print ("This line will always print")


The file does not exist, exiting gracefully
This line will always print
>>>

Using the built−in open function, you can try to open a file for reading (more on open in the next section).
But the file doesn't exist, so this raises the IOError exception. Since you haven't provided any explicit check
for an IOError exception, Python just prints out some debugging information about what happened and then
gives up.

You're trying to open the same non−existent file, but this time you're doing it within a try...except block.

When the open method raises an IOError exception, you're ready for it. The except IOError: line
catches the exception and executes your own block of code, which in this case just prints a more pleasant error
message.

Once an exception has been handled, processing continues normally on the first line after the try...except
block. Note that this line will always print, whether or not an exception occurs. If you really did have a file
called notthere in your root directory, the call to open would succeed, the except clause would be
ignored, and this line would still be executed.

{source}
<!-- You can place html anywhere within the source tags -->
<pre class="brush:py;">
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.

>>> fsock = open("/notthere", "r")
Traceback (innermost last):
File "<interactive input>", line 1, in ?
IOError: [Errno 2] No such file or directory: '/notthere'
>>> try:
    fsock = open("/notthere")
except IOError:
    print ("The file does not exist, exiting gracefully")
    print ("This line will always print")


The file does not exist, exiting gracefully
This line will always print
>>>


</pre>

<script language="javascript" type="text/javascript">
    // You can place JavaScript like this

</script>
<?php
    // You can place PHP like this

?>
{/source}

Exceptions are everywhere in Python. Virtually every module in the standard Python library uses them, and Python
itself will raise them in a lot of different circumstances. You've already seen them repeatedly throughout this book.
· Accessing a non−existent dictionary key will raise a KeyError exception.
· Searching a list for a non−existent value will raise a ValueError exception.
· Calling a non−existent method will raise an AttributeError exception.
· Referencing a non−existent variable will raise a NameError exception.
· Mixing datatypes without coercion will raise a TypeError exception.