Hello Friends, I am back again with some interesting and exciting topic i.e Python Exceptions.Today we’ll deal with Python Exceptions class to handle unexpected errors that occur during execution of the program.Not only Python Exceptions class handle Errors but also it provide Debugging facilities.
Python Exceptions Handling
What is Exception?
An exception is an event, that occurs during the execution of a program, that disrupts the normal flow of the program’s instructions. In general, when a Python script encounters a situation that it can’t handle with, it raises an exception. An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception immediately otherwise it would terminate and come out.
How and When to Handel Exception ?
Suppose you have written any code and you know that this code may throw an error, so to defend it we use Exception by putting your code in a try: block followed by except block where you handle you errors.
try: write your code here except Exception: If error occurs, programme will execute this block
Here are few important points about the above-mentioned syntax:
- A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.
- You can also provide a generic except clause, which handles any exception.
- After the except clause, you can include an else-clause. The code in the else block executes if the code in the try: block does not raise an exception.
- The else-block is a good place for code that does not need the try: block’s protection.
Lets create one Example
import MySQLdb try: db=MySQLdb.connect("localhost","root","pass","Language" ) cursor = db.cursor() sql = "SELECT * FRON Python except MySQLdb.Error, e: print "Error occurc due to",e try: cursor.execute(sql) db.commit() except MySQLdb.Error, e: print "Error occurc due to",e db.close()
You can use many Exception in except clause and you can also use else statement as the else-block is a good place for code that does not need the try: block’s protection
try: write your code here except Exception1,Exception2,..ExceptionN: If error occurs, programme will execute this block else: If Exception is not occurring then execute this block
import MySQLdb try: db = MySQLdb.connect("localhost","root","pass","Language" ) cursor = db.cursor() sql = "SELECT * FRON Python except MySQLdb.Error, e: print "Error occurc due to",e try: cursor.execute(sql) db.commit() except MySQLdb.Error, e: print "Error occurc due to",e else: results = cursor.fetchall() for row in results: Language = row[ 0 ] uses = row[ 1 ] print "Language=%s,uses=%s"% (Language, uses ) db.close()
There is finally block that use with try clause.
The finally block is a place where you put any code that must execute,
whether the try-block raised an exception or not.When an exception occurs the execution immediately passes to the finally block and execute the code that is inside finally blocked.You can use Nesting of Exception Handling.The syntax of the try-finally statement along with Nesting
try: write your code here except Exception: If error occurs, programme will execute this block finally: This block always executes whether the try-block raised an exception or not
try: try: x = raw_input ('Enter a number for the dividend: ') y = raw_input('Enter a number to divisor: ') finally: x = int(x) y = int(y) except ValueError: # handle exception and move to outer try-except print 'You must enter a numeric value!' z = x / y except ZeroDivisionError: # handle exception print 'You cannot divide by zero!' except TypeError: print 'Retry and only use numeric values this time!' else: print 'Your quotient is: %d' % (z)
Python allows you to create you own different type of exception by extending classes of built-in Exception.let take an example to clear this concept
class My_Io_Exception(IOError): def __init__(self, arg): self.args = arg
Now the code for raising our newly define exception.It occurs if our code raises exception
try: f = open("pythonlovers.txt", "r") try: f.readline() finally: print "closed the pythonlovers.txt file" fh.close() except My_Io_Exception,e: print "Error occurs due to ",e.args
Here is the list of Exception that occurs during Program Execution
Hope guys you will understand the concept of Python Exception handling clearly.Try to implement it with more code, and if you find any difficulty, feel free to drop a comment on this post.