analitics

Pages

Friday, September 11, 2009

How to use "try" ... "except"

Any program will be given over to error checking.
Python provides an exception handling capability.
There are two parts : "error checking" "catching exceptions".
Now let's try a simple example:

>>> try :
... input_str = int(input ("string "))
... except StandardError :
... print " This is not a number"
...
string 12
>>> try :
... input_str = int(input ("string "))
... except StandardError :
... print " This is not a number"
...
string aaa
This is not a number

The code :
input_str = int(input ("string "))

The code readed input will be convert in integer .
If types a value that's not an integer, the exception is caught.
In this case will print " This is not a number ".
This is very important because it generates more errors while running a program.
So, simply try to perform you action, and define what's to be done.
On except block if the action you want can't be completed.