Monday, 21 May 2018

Exception Handling with Python


When an exception is raised it causes the program to terminate and it is called as an Unhandled Exception. If we know that a line of code might raise an exception when executed we should handle the exception.

What is an Exception
An exception is an event , which occurs during the execution of a program that disrupts the normal flow of the program's instructions. When a python script encounters a situation that it cannot cope with , it raises an exception . An exception basically represents an error.


Handling an Exception 
Exceptions can be handled to avoid program from crashing , this is called Exception handling.
When we can anticipate an error in the program we can use exception handling to stop the program from crashing.

Syntax for exception handling : 

try:

except.............

print 

Example
If we know that in a program we can get such values that a ZeroDivisionError can occur , so we can handle this by except ZeroDivisionError :

>>> while True:
try:
    x = int(raw_input("Please enter a number: "))
    y = int(raw_input("Please enter a number: "))
    z = x/y
    break
        except ZeroDivisionError:
            print "Oops!  That was no valid number.  Try again..."

            
Please enter a number: 3
Please enter a number: 0
Oops!  That was no valid number.  Try again...
Please enter a number: 

First the try clause is executed, if an exception occurs the try block code execution is stopped and handled in except block.. The message given in exception block is printed and execution again passes to try block.

No comments:

Post a Comment

Loan Prediction Analysis

In this post I will share my visuals ,learning and understanding of a dataset and using various algorithms of Machine Learning to analyse i...