top of page
  • Writer's pictureJatin Madaan

Exceptional - Handling


This post is about very basics of exceptional handling .


Exceptions - It is a type of error if not taken care of then code may crash . To avoid crash and handle at programmer level we handle the exceptions (or know error/issues) .


eg :




def factorial (n):
    if n<=1:
        return 1
    else:
        return n*factorial(n-1)
        
print(factorial(10000))

O/P :

---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)
<ipython-input-6-82c3e39cc340> in <module>
      5         return n*factorial(n-1)
      6 
----> 7 print(factorial(10000))

<ipython-input-6-82c3e39cc340> in factorial(n)
      3         return 1
      4     else:
----> 5         return n*factorial(n-1)
      6 
      7 print(factorial(10000))

... last 1 frames repeated, from the frame below ...

<ipython-input-6-82c3e39cc340> in factorial(n)
      3         return 1
      4     else:
----> 5         return n*factorial(n-1)
      6 
      7 print(factorial(10000))

RecursionError: maximum recursion depth exceeded in comparison

Here RecursionError is an error occurred which crashed the code .


We can handle these kinds of error to not crash code (For this we use try and except block ) :


eg :



def factorial (n):
    if n<=1:
        return 1
    else:
        return n*factorial(n-1)
 
try : 
    print(factorial(10000))
except RecursionError: 
    print("Program cannot handle this much data")

## This would be printed post try and except block (in case of failure/success below command would be printed ). 
print("Program ENDED")

O/P:

Program cannot handle this much data
Program ENDED

Handling multiple exceptions using different except block :



## Multiple exceptions

def factorial (n):
    if n<=1:
        return 1
    else:
        print(n/0)
        return n*factorial(n-1)
 

try : 
    print(factorial(10000))
except RecursionError: 
    print("Program cannot handle this much data")
except ZeroDivisionError:
    print("Divide by 0 is not possible")

print("Program ENDED") 

O/P :



Divide by 0 is not possible
Program ENDED

eg : Multiple exceptions with same error



## Multiple exceptions with same error message 

def factorial (n):
    if n<=1:
        return 1
    else:
        print(n/0)
        return n*factorial(n-1)
 

try : 
    print(factorial(10000))
except (RecursionError , ZeroDivisionError): 
    print("Either there is too much \
data or you are diving with 0")

O/P :


Either there is too much data or you are diving with 0 

Finally


Sometimes it is necessary to run a code whether exception occurred or not ie code in finally block will always execute .


For example in case of database transactions we need to close the connection irrespective of any failure or success .


eg :



def factorial (n):
    if n<=1:
        return 1
    else:
        #print(n/0)
        return n*factorial(n-1)
 

try : 
    print(factorial(10))
except (RecursionError , ZeroDivisionError): 
    print("Either there is too much \
data or you are diving with 0")
finally :
    print("This will always run")

O/P :

3628800
This will always run

ELSE in try/except :


In case we want to execute something in case there is no exception raise we can use else block .


eg :


def factorial (n):
    if n<=1:
        return 1
    else:
        return n*factorial(n-1)
 

try : 
    print(factorial(10))
except (RecursionError , ZeroDivisionError): 
    print("Either there is too much \
data or you are diving with 0")
else :
    print("This will run in case no exception")

O/P:



3628800
This will run in case no exception

In Python exceptions are objects & must be derived from a class .


Also there is an option to catch every exception using Exceptions only which must be included in last post all except block.


eg:




## Catch every exception 

def factorial (n):
    if n<=1:
        return 1
    else:
        #print(n/0)
        return n*factorial(n-1)
 
try : 
    
    print(factorial(10000))

except ZeroDivisionError:
    print("Divide by 0 is not possible")
except Exception:
        print("In case of any exception\
 which is not given above this is called") 

O/P:



In case of any exception which is not given above this is called 

Raising an exception :


The raise statement allows the programmer to force a specified exception to occur at any point of code.



eg:



def factorial (n):
    if n<=1:
        return 1
    else:
        #print(n/0)
        return n*factorial(n-1)
 
print(factorial(10))

raise Exception("Sorry, no numbers below zero") 

O/P :


3628800 

--------------------------------------------------------------------------- Exception                                 Traceback (most recent call last) <ipython-input-42-8a9696b5ab95> in <module>       9      10 print(factorial(10)) ---> 11 raise Exception("Sorry, no numbers below zero") Exception: Sorry, no numbers below zero


User Defined Exceptions :



Programs may name their own exceptions by creating a new exception class .Exception should typically be derived fro Exception class ,either directly or indirectly .


Eg :



## User-Defined Exceptions 


class User_Error(Exception):
   def __init__(self, value):
      self.value = value
   def __str__(self):
      return(repr(self.value))
try:
   raise(User_Error("We can type in any new error details here !"))
except User_Error as error:
   print('A New Exception occurred:',error.value)

O/P :



A New Exception occurred: We can type in any new error details here ! 

This was introduction to Exception handling in Python .



15 views0 comments

Comments


bottom of page