Tag Archives: Exception Handling

Custom Exception Handling in Python

Hello folks, In the previous post we have got the basic understanding of Exception handling in python. And, Today’s agenda will be custom exception handling – how we can force raise an exception, define and create custom Exception classes.

Let us imagine you need to write a code to validate your input and the validation criteria is input should be an integer and it should be between 1 to 10. If the validation criteria fail, we have to throw valid exceptions.

My first solution will be something like this.

def isvalid_input(val):
    try:
        if(val > 0 and val <= 10):
            print('input is valid')
        else:
            print("input is invalid")
    except Exception as ex:
        print(ex)

But in this code we have ignored various scenarios like

  • Input maybe not integers and then mathematical operators will not work and it will throw an exception.
  • we are not actually raising an exception if the validation criteria do not match.

Raise Custom Exception

so let us say how can we force raise any exception. To do it, we use the raise keyword in python. so modify the above code and use the raise keyword in the else block.

def isvalid_input(val):
    try:
        if(val > 0 and val <= 10):
            print('input is valid')
        else:
            raise Exception("Input is Invalid")
    except Exception as ex:
        print(ex)

Create Custom Exception Class

Now what we want to do is to handle the validation criteria and throw custom exceptions based on validation criteria. so create custom Exception classes.

class VALRANGEERROR(Exception):
    def __init__(self,message):
        self.message=message
        super().__init__(self.message)

Here we have created a class called VALRANGEERROR and setting its message in constructor so that we can provide custom messages while raising this exception. After this modify our method to raise our custom Exception class.

def isvalid_input(val):
    try:
        if(val > 0 and val <= 10):   
            print('input is valid')
        else:
            raise VALRANGEERROR("Input is not in range")
    except ValueError as ex:
        print(f"Value Error - {ex}")
    except VALRANGEERROR as ex:
        print(f"Custom Exception - {ex}")
    except Exception as ex:
        print(ex)

So, to summarise this, use the raise keyword to force raise an exception. To implement a custom Exception class, Create a class that inherits from class Exception and assigns the message field in the constructor.

Exception handling in Python

Exception or Error

There can be 2 type of error – Syntax Error or Exceptions.

Synax error encounters if you do not follow language syntax guidelines. common scenarios to face such errors are:

  1. you do not follow proper indentation.
if a= 0 print(a) else print('NA')

2. Suppose you have a method which takes 2 arguments and while calling it, you are providing only one argument.

def return_sum(a,b):
    return a+ b

val = return_sum(3)

There are multiple scenarios like this. In short, a syntax error occurs if the python interpreter fails to parse your code. Now let us discuss exception.

Exceptions are any unwanted thing which may interrupt the control flow of program.

Common Exceptions which you may face with python are – Name Error, Type Error, Runtime Error, or when you are working with files. In short, we can call exception as error faced while coding execution.

a = 10
b = a/0
 #Division by 0 Error
print("Var"+ 1) #Type Error 
print(c) #Name Error
with open('filedoesnotexist') as f: #OSError
    f.read()

your code will break as the exception encounters. Here you can see that control flow of the program is stopped because of ZeroDivisionError and that’s why the code below that statement never gets executed.

Exception Handling

To solve these scenarios we need to perform exception handling. If I am asked to give a crisp description of these keywords, I will say something like this.

put your IO method or DB related methods in a try block in which you think exception may occur. If an exception occurs, Handle it in Except block. If there is no exception, Put it in the else block. And if you want to run some methods whether exceptions are encountered or not, put it in finally block like cleaning up activity, closing the DB connections or releasing the resources.

There are 4 Keyword for Exception handling in python.

  • Try: Run this code
  • Except – Run this code if Exception occurs
  • Else – Run this code if Exception does not occur
  • Finally – Run this code always whether an Exception occurs or not.

Let us consider you want to write a program to get the value of a variable from a file and then delete it. If the file does not exist then you reset the value to 0 in the file.

import os
val=None
try:
    with open('filedoesnotexist.txt') as f:
        val = f.read()
except Exception as identifier:
    val=0
    with open('filedoesnotexist.txt','w') as f:
        f.write(str(val))
else:
    os.remove('filedoesnotexist.txt')
    print("Exception did not occured. Good Job")
finally:
    print(val)
    

To avoid the Name Error i have created val variable globally as it is being used in try, except and finally block. There is Input output operation so i have put the logic to read filedoesnotexist.txt in try block. If the file does not exist, we are resting the value of val to 0 and writing it to filedoesnotexist.txt. And if the file exists then we will not get any error so i am deleting that file and finally printing the value of val variable.

I Hope you got the basic idea of Exception handling. In the next post, I will tell you how to raise custom exception, create user defined Exception and how to debug the stack trace.