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
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. So, if we add finally to the above example the result will be as follows:
Now look at the following example:
When you enter a number, there is no issue, but anything other than that will result in error. So, we can use try-except as shown below:
Remember that if you don’t specify an exception type in except block, then it will catch all exceptions.
Get Updates on Tech posts, Interview & Certification questions and training schedules