Exception Handling in Python

 Exception Handling in Python


Errors in Python:

We are human beings, we commit several errors. Software developer or programmer is also human being and hence errors might be occur in software or programs. To get desired output these errors should be detected and removed from program. This error handling process is called debugging.

In Python there are following types of errors,

  1. Compile Time Errors:

These are syntax errors that occur at the time of program compilation and hence program fails to compile. For example colon missing error occur when you miss to use it when you use if, else, for, while, def etc methods in python.

2. Run Time Errors:

These errors are occurring when you execute your program. When python virtual machine can not execute the byte code. The runtime errors cannot detected by python compiler, it is detected by PVM at the runtime.

For example,

TypeError: Can’t convert ‘int’ object to ‘str’ implicitly

3. Logical Errors:

These errors are occurred due to incorrect logic or incorrect formula. These errors are not detected by python compiler or PVM. Due to incorrect logic programmer will get incorrect output. 


What is Exception Handling?

Compile time and logical errors can be handled by programmer by modifying source code. But in case of run time errors, if programmer knows which type of errors occurs he has to handle them with exception handling. The run time errors which are handled by programmer are called exception. If programmer know what type of error occur in the program execution the he can eliminate these errors by using a program code is called exception.

Exception is a simple code which is used to handle any anomaly or disrupts in normal flow of instructions. When errors are handled with these instructions written by programmer is called exceptions.

Following are some built in Exceptions

ArithmeticError:  like overflowError, ZeroDivisionError, FloatingPointError etc

AttributeError:  Raised when an attribute reference or assignment fails

EOFError: Raised when an input() reaches end of file condition without reading any data.

IOError: Raised when input or output function fails

ImportError: Raised when an import statement fails

IndexError: Raised when sequence index or subscript is out of range.

NameError: Raised when an identifier is not found locally or globally

OverflowError:  Memory error

SyntaxError: Raised when compiler encounters a syntax error

ZeroDivisionError: Raised when denominator is zero in divison



Examples,

1. Syntax Errors

# Syntax Errors

a=100 

if a>200

print("A is bigger")


Error:

 SyntaxError: invalid syntax (<ipython-input-1-4f1526972cc6>, line 2) 

  File "<ipython-input-1-4f1526972cc6>", line 2

    if a>200

            ^

SyntaxError: invalid syntax


Exceptions are raised when programs are syntactically correct but code result in wrong result.  It changes normal flow of program.


For Example,


# ZeroDivisionError

amount=1000 

discount= amount/ 0

discount


Error:

ZeroDivisionError: division by zero 


 In the above example raised the ZeroDivisionError because here we are trying to divide amount by 0. 

Exception Handling Methods in Python:


Try and Except Statements:

The try and except statements in Python are used to handle or catch the exceptions. The statements which raise the exceptions are kept in try block and statements that handle exceptions are kept inside the except block. 

For example, 


# Python program to handle error at runtime

arr=[1,2,3,4,5,6,7]

try:

    print("The third element is",(arr[2]))

    

    print("The 8th element in list",(arr[4]))

    

    #Throws error since there is no 8th element in list

    print("The 8th element is",(arr[7]))

except:

    print("The Error occured") 


O/P:

The third element is 3

The 8th element in list 5

The Error occurred


In the above example the statements that is causing error is written in try clause and this statement throws an exception and this exception is caught by except clause.


Try With Else Clause in Python:

Else clause is used to in try except clause which can be written after except clause. The else code only enters if try block does not raise exception. 


Example,

# else clause

def sample(x,y):

    try:

        operation=((x+y)/(x-y))

    except ZeroDivisionError:

        print("The result in 0")

    else:

        print("The result is",operation)

sample(5.0,3.0)

sample(10.0,10.0)


O/P:

The result is 4.0

The result in 0


In the above example function sample have operation on x and y variable i.e. addition of ax an y is divided by subtraction of x and y.  The in first function call values are passed which does not result in ZeroDivisionError so exception thrown to else block. 


Finally Statement in Python:

The finally block is executed after the try and except block. This block will get execute after normal termination of try block.


For example,

# Finally block/ statement in Python

try:

    a=100/0

    print(a)

except ZeroDivisionError:

    print(" 100 can not divided by 0")

finally:

    print(" This block always executed")

O/P

100 can not divided by 0

 This block always executed

 

Raising Exception Statement in Python:

The raise statement is used to force a specific exception to occur. The argument in raise statement indicates the exception to be raised. 


For example,


# The raise statement in Python

try:

    raise NameError(" Hello friends")

except NameError:

    print("An exception ocured")

    raise


O/P:

An exception ocured

 NameError:  Hello friends 


Write a python program which consists of - try, except, else, finally blocks


# program to print the reciprocal of even numbers


try:

    num = int(input("Enter a number: "))

    assert num % 2 == 0

except:

    print("Not an even number!")

else:

    reciprocal = 1/num

    print(reciprocal)

finally:

    print('finally')


O/P:

Enter a number: 45

Not an even number!

finally


टिप्पणी पोस्ट करा

0 टिप्पण्या