Python try-except

If you know that there are chances that your code may produce error at the run time due to various unavoidable factors, you can handle those errors elegantly by using a try-except block. For example a divide by zero, connection to db error, page not found error etc.

Consider below example, if the value of y is equal to zero, then the code which divides 100 by ‘y’ will execute. if there is no try catch block, then the program will result into an error as shown below

Python Division by zero error

When you add a try-except block, you can handle the above situation elegantly, without your program crashing with error.

Sample Output:

Python exception handling using Try-Except block
Python Try-Except block

Author Details
Lead Data Scientist
Farukh is an innovator in solving industry problems using Artificial intelligence. His expertise is backed with 10 years of industry experience. Being a senior data scientist he is responsible for designing the AI/ML solution to provide maximum gains for the clients. As a thought leader, his focus is on solving the key business problems of the CPG Industry. He has worked across different domains like Telecom, Insurance, and Logistics. He has worked with global tech leaders including Infosys, IBM, and Persistent systems. His passion to teach inspired him to create this website!

Leave a Reply!

Your email address will not be published. Required fields are marked *