Python exception handling example

In any application development often we implement error-handling mechanism, in this article you will learn how to raise error and handle exception in python application development, and what are the different type of error classes available in python programming.

As we know error or exception handling is one of the most important factors in software development, and every programming language provide different ways of handling exception.

Here we learn some best error handling techniques in python application development.

Error handling in Python

We are probably all familiar with try catch block for error handling in different programming languages, in python we have something very similar is try- except below is the very standard error handling we often write in python function implementation.

def functionName(self , param): 
    try: 
        # some code here
    except mysql.connector.Error as error:
        print("Error while reading from MySql", error)
    finally:
        #Do whatever you want 

There are different types of error class in python; you need to use relevant error class depending on what type of python project implementation you are working on.

Here are few common error classes in python

  • SyntaxError
  • ZeroDivisionError
  • NameError
  • TypeError

You also can catch multiple type of errors in one except code block using parenthesis like (errorOne, errorTwo, errorThree). look at the example below.

def StartCrawling():
    try:         
        print("Action Success")      
     
    except (ZeroDivisionError, SyntaxError, NameError):
        print("Error occurred")
    finally:
        print("Done!")
Raise an exception

You can raise error from python code based on business requirement or situation. The raise keyword is used to raise any new exception.

def CheckAge(self, age):
if age < 18:
        raise Exception("Age should be more than 18"); 

We can check any specific data type; if not matching we can raise error in python code.

def CheckAge(self, age):       
     if not type(age) is int:
            raise TypeError("Age should be integer only");

In real-time application development, after catching the error details you may either log error details or send an email to admin users, or do both, following post may be helpful for you.

 
Python exception handling
Like any other programming language, there are some good practices for error handling in python coding.
Learn python programming with free python coding tutorials.
Other Popular Tutorials
Python error handling
Python programming examples | Join Python Course