Sunday, June 26, 2011

Exceptions and Exception Handling


In this post I want to explain about the exception handling in Python.

Exceptions are the run time errors and we usually get this error when we run the code. These exceptions can be efficiently handled using some techniques. Exceptions arof different types and most common exceptions are ZeroDivisionError, NameError and TypeError.

ZeroDivisionError exception occurs when we try to divide by 0.

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

The last line of the error message shows the type of exception.

NameError occurs when we try to process on an undefined variable.

>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined

TypeError occurs when variables of different types are used in an expression.

>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects

Other main exceptions are,
AssertionError, AttributeError, EOFError, OverflowError, IndentationError, ValueError etc

We can handle these exceptions by writing codes for them. We can add a ‘try/except’ structure to your code to handle exceptions.

When we write the try and except clauses, first the try clause is executed. If no exception occurs, the except clause is skipped and execution of the try statement is finished. If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement. If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.

Example code is given below.

If the we want to get an integer number as an input we can write the following code,

x = int(raw_input("Please enter a number: "))

But if the user inputs a non-integer value it will print an exception of type ValueError.
Here we can handle this exception by using the try and except. Look at the code given below.

try:
    x = int(raw_input("Please enter a number: "))
    break
except ValueError:
    print "Oops!  That was not a valid number.  Try again..."

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:

except (RuntimeError, TypeError, NameError):
    print “Enter a valid option”

We can also use except without any exception names. Look at the code below.

except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

The try/except statement has an optional else clause, which must follow all except clauses.


try:
    f = open(arg, 'r')
except IOError:
    print 'cannot open', arg
else:
    print arg, 'has', len(f.readlines()), 'lines'
    f.close()


These are basic details about the exceptions and their handling.

Thanks

AJAY

No comments:

Post a Comment

Comments with advertisement links will not be published. Thank you.