Mindmajix

Python exception handling

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 :

Screenshot_36

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

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.

Screenshot_37

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:

Screenshot_38

Now look at the following example:

Screenshot_39

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:

Screenshot_40

Remember that if you don’t specify an exception type in except block, then it will catch all exceptions.

https://docs.python.org/2/tutorial/errors.html

Enroll for Instructor Led Live Python Training

 


0 Responses on Python exception handling"

Leave a Message

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

Copy Rights Reserved © Mindmajix.com All rights reserved. Disclaimer.
Course Adviser

Fill your details, course adviser will reach you.