Free Web Development Online Tutorials, Learn to Code
Python Error handling best practices, how to handle exception in python code

Python exception handling example

In this article you will learn how to handle exception in Python application development

Error handling in Python

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 development.

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 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 your 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");
 
Python exception handling

Python error handling
Python programming examples | Join Python Course