Exception Handling in Python

Exception Handling in Python

You know you get serious with Python programming language when you start to learn about exception handling. But why do we need exception handling?

The best way to understand exception handling in Python and why do we need it is to look at examples and practice all the time. Sometimes, even if your programs’ syntax is right and you are sure everything is ok, when you execute your Python programs, it gives you errors and stops executing. A classic example that explains exception handling very well is division by zero. Open the Python in interactive mode and try to divide a number by zero. What happens? Everything is correct, your syntax is OK and you wondering why is this happening, why does the program print error and stop running? Wait, let me open a terminal and see what kind of error it is.


Figure 1


Figure 2


Figure 3

Hmm, “ZeroDivisionError: integer division or modulo by zero”. If you know basics in math, you know that you can not divide a number by zero and now that you are reading Unixmen’s article you understand that in computing, dividing by zero crashes the program and return an error. Now, how can we make the program continue working, even if the users want to perform that kind of operation? Imagine a situation where you have to build the calculator and you are not allowed to filter user input, what happens if the user want to divide a number by zero? The calculator will stop working and giving errors to the user, that’s what happens.

Imagine another situation where you have to connect to 100 SSH servers and verify if they are alive, but have you ever thought that one server can back you down? You connect to the first server, to the second and they are up, you try to connect to the third server and the script stops working because the third machine which you are trying to connect is not running SSH at all. Your script stops working, you have no information about other 93 machines, your energy, time and money are gone. Your boss is angry with you and he is thinking to fire you or giving you extra work. If you don’t want to be in this bad situation you have to learn how to do exception handling. We will use try in Python, except our error, store it into a variable and then print this variable to inform the user about the error and why does it happen. This way the user is happy and the program continues executing the other piece of its code.

As I mentioned before, the best way to understand exception handling is to see it in practice, so the figure below explains everything and I have commented each line of the script for you to understand. This is a simple example which will help you to understand exception handling without struggle.


Figure 4

As you can see from Figure 4, when a program is executed it does not gives us error because we used exception handling, we linked error to variable e and printed it out to inform the user about the division by 0. We used ‘except Exception,e’, which is part of Python’s syntax to handle the error and link it to variable.

  • pip010

    this is pretty weak article.
    the main topic should be why not simply return err_code from each method call?
    why exceptions?

  • Ambiton

    I am sorry mate, but i do not understand what is the problem with my article, i think the problem is with you,Google exception handling in Python and you will understand why my article is called so.If you need any help i am here :)

  • pip010

    it is a nice introduction for beginners. but it falls short to give clues to the reader why errorhandling via exception is superior to alt., let’s say C style returning error_code.

    things like:

    – the stack unwind and cleaning temp/resources

    – the possibility to traceback and receive ‘stack trace’ of invocation

    so a python developer, should know to throw! and not return!

    how about the dark side of exceptions?

    throwing exec while handling exec?
    handling generic except:
    like maybe you don’t need exception handling, instead use: using expressions.

    just saying…

  • Ambiton

    I think you should have done this comment before :) Thank you very much for your information, this article is for beginners because it is an introduction to exception handling,you can not call it weak because being for beginners and being weak are two different things.I like your idea about using expressions but this article is an introduction to exception handling,not about which method is the best, the title says that.

    Regards :)

  • pip010

    even for beginners, it is worth at least mentioning WHY exceptions. it is important, i hope you agree, to understand any feature you use in a lang/framework. it is not about style! and going the return err_code is IMO not arguable by any chance a very bad practice, that is: DON’T DO IT and always use exceptions. something I hope you agree a novice to python and/or programing in general will most likely do, because is the least friction (easy and straightforward).

    Please, don’t take it personal for calling it a weak article, but I fail to see what it brings to the table, compared to any other!

  • f2082542

    Very very weak article.

    print “ERROR”+str(e).

    Why is that ? Why not use print “ERROR”, e

    Also, who makes screenshots instead of code paste ?