How to do Exception handling in python??

               A good developer knows about the structure of proper coding. It’s always good to practice exception handling mechanisms.

In python, we have the following mechanisms for exception handling.

  1. try except
  2. try, except, else
  3. Using finally

1.try except exception handling:

              This is the common method used in many languages. Try is the beginning keyword. It follows a coding block and end by a keyword “except” follows a statement.

Syntax:

try:

 coding block

except:

 a line of statement.

For example,

#Get a float number

a = float(input("Enter the number"))

#Create a try except block using the print statement.

try :

     print(a/0)

except:

     print("Exception occurred")

The outcome of this program is

Enter the number 45.7

Exception occurred

2.try,except,else:

              When a condition occurs, the user has two options. Either true or false. If the condition is true, it follows a set of statements. Otherwise, if one more control statement occurs, it follows another set of statements.

Syntax:

 try :

       ----------

       ----------

except :

    ------------

    ------------

else :

     ------------

     ------------

Example:

#Enter the two values a and b.

a = int(input("Enter the numerator"))

b = int(input("Enter thedenominator"))

#use the values for division. If the denominator is zero. It creates an exception. Else it prints the output.

try:

     d = a/b

except:

         print("Your denominator value is zero. please change it to non zero value")

else:

        print("Your answer is",d)

output:


  3.Using finally:

This is one of the error handling mechanisms in python. This keyword “finally” can be added in the code to execute the final statement in the block

Syntax:

---------------

---------------

finally :

Set of statements to execute…….

Eg:

#create a function fn_final(). Print the values according to the flow of control. Add the print statement to try,except and else block.

def fn_final():

    try:

        print("The control is in try block")

    except exception as er:

        print(er)

    finally:

        print("The control is in finally block")

  #call the function and print the returned value.     

print(fn_final())

These are the error handling mechanisms in python.

No comments:

Post a Comment