Articles

Python Exception Handling

by Azhar Uddin Technical Architect

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal. Exceptions help in handling errors in a convenient way so that your program does not crash. Exception handling should be used when you feel that you have a code that is capable of producing an error. It is possible to write programs that handle selected exceptions.

You can also raise an exception in your code, this breaks the execution of the code and returns an exception.

Within Python, you may encounter the following exception :

Exception handling blocks are created with the help of “try” and  “except” keywords. The simplest way to handle exceptions is with a “try-except” block. The format is as follows:

try-except[exception_name]

The code that needs to be executed is placed in the ‘try’ block and in case an exception occurs, the rest of the lines in the code will not be executed.

Try:
your_code

Except:

code for handling exception

Learn how to use Python, from beginner basics to advanced techniques, with online video tutorials taught by industry experts. Enroll for Free Python Online Training Demo!

Look at the following example where first an attempt is made to divide a number by zero without exception handling. In the second attempt try-exception combination is used. See the results for yourself, preferably, try them out yourself.

With the try-exception blocks you can also use ‘ finally ’ block and the code written here is executed whether an exception is raised or not. 


Sponsor Ads


About Azhar Uddin Advanced   Technical Architect

42 connections, 1 recommendations, 209 honor points.
Joined APSense since, May 12th, 2017, From Hyderabad, India.

Created on Aug 21st 2018 05:31. Viewed 262 times.

Comments

No comment, be the first to comment.
Please sign in before you comment.