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