You are on page 1of 3

Home (/) >> Try and Except in Python

Sep. 30, 2012

Error Handling (/error-handling/)

Try and Except in Python


Earlier I wrote about Errors and Exceptions (http://www.pythonforbeginners.com/error-handling/python-errors-
and-exceptions/) in Python. This post will be about how to handle those. Exception handling allows us to
continue our program (or terminate it) if an exception occurs.

Error Handling
Error handling in Python is done through the use of exceptions that are caught in
try blocks and handled in except blocks.

Try and Except


If an error is encountered, a try block code execution is stopped and transferred
down to the except block.

In addition to using an except block after the try block, you can also use the
finally block.

The code in the finally block will be executed regardless of whether an exception
occurs.

Raising an Exception
You can raise an exception in your own program by using the raise exception
[, value] statement.

Raising an exception breaks current code execution and returns the exception
back until it is handled.

Example
A try block look like below

1 of 11
try:
print "Hello World"
except:
print "This is an error message!"

Exception Errors

Info Info

Some of the common exception errors are:

IOError
If the file cannot be opened.

ImportError
If python cannot find the module

ValueError
Raised when a built-in operation or function receives an argument that has the
right type but an inappropriate value

KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete)

EOFError
Raised when one of the built-in functions (input() or raw_input()) hits an
end-of-file condition (EOF) without reading any data

Example
Let's have a look at some examples using exceptions.

2 of 11
except IOError:
print('An error occured trying to read the file.')

except ValueError:
print('Non-numeric data found in the file.')

except ImportError:
print "NO module found"

except EOFError:
print('Why did you do an EOF on me?')

except KeyboardInterrupt:
print('You cancelled the operation.')

except:
print('An error occured.')

There are a number of built-in exceptions (http://docs.python.org/library/exception


s.html) in Python.

Recommended Python Training DataCamp


(https://www.datacamp.com/courses/tech:python?tap_a=5644-
dce66f&tap_s=75426-9cf8ad)
For Python training (https://www.datacamp.com/courses/tech:python?tap_a=5644-dce66f&
tap_s=75426-9cf8ad), our top recommendation is DataCamp.

Datacamp (https://www.datacamp.com/courses/tech:python?tap_a=5644-dce66f&tap_s=75426-9cf8ad)
provides online interactive courses that combine interactive coding challenges with videos from top instructors
in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

3 of 11

You might also like