Exception Handling in Python


Python provides two very important features to handle any unexpected error in your python programs which are given below-

1. Exception Handling

2. Assertions

Let us discuss one by one-

1. Exception Handling

Exception 

 Exception are a type of interrupt from which our program can be terminate. Exception is an abnormal condition. An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the programs instructions. In general, when a python script encounters a situation that it can not cope with, it raises an exception.

When a python script raises an exception, it must either, handle the execution immediately otherwise it terminates and quits.


Handling an 
Exception

  To handle the exception in python program we can use the try-except block.
If you have some suspicious code that may raise an exception. You can defend your program by placing the suspicious code in the try block.

After the try : block , include an except : statement followed by a block of code which handles the problem as elegantly as possible.

A single try statement can have multiple except statements . This is useful when the try clock contains statements that may throw different types of exceptions.

A try block can not come alone at least one except block will be acceptable with the try block.

You can also provide a generic except clause, which handles exception.

After the except clause(s), you can include an else block. the code in the else block executes if the code in the try : block does not raise an exception.

Syntax

try:

       # You do your operations here

except Exception1:

        # if there is exception1, then execute this block

except Exception2:

        # if there is exception2, then execute this block

else:  
        If there is no exception, then execute this block

Example

This example opens a file (which is already exist) write content in the file and comes out gracefully because there is no problem at all.

try:  

    fh=open("textfile", "w")

    fh.write("This is my first file for exception handling")

except IOError:

    print("Error: can not find file or read data")

else:

    print("written content in the file successfully")

    fh.close()

Output

written content in the file successfully

Example

This example tries to open a file (which is already exist) where you do not have write permission, so it returns an exception.

try:  

    fh=open("textfile", "r")

    fh.write("This is my first file for exception handling")

except IOError:

    print("Error: can not find file or read data")

else:

    print("written content in the file successfully")

    fh.close()

Output

Error: can not find file or read data

The try-finally block

  You can use a finally block along with a try. The finally block is a place to put any code that must execute, whether the try block raised an exception or not.

Syntax

try:

        You do your operations here.

finally:

        This would always be executed.

You can not use else block as well along with a finally block.

Example

try:

        fh=open("textfile","w")

        fh.write("this is my text file for exception handling")

finally:

        print("Error : can not find file or data")

Output

Error:can not find file or data

       


    

    
















         







No comments:

Post a Comment