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

When you add a try-except block, you can handle the above situation elegantly, without your program crashing with error.
1 2 3 4 5 6 7 8 9 10 11 12 |
## Example for try-except block y=0 if(y==0): try: print('Result:',100/y) except Exception as exceptionMsg: print('Something went wrong!', exceptionMsg) else: print('Condition is not true') |
Sample Output:

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!