In any programming, including Python, exceptions and error handling often becomes a necessity when you are dealing with a considerable amount of variables. When, I say variables I do not mean variables as a placeholder, but variables as in you are using file system processes (like reading a file), dealing with external input, etc. Sometimes, you just do not know what will be thrown at your code. So you being little genius, you plan ahead and use exceptions and error handling where appropriate. Typically, the goal is to execute the code as intended, but if an exception occurs, we would prefer Python not to spit out its own exceptions. Instead, we would like to inform the user what went wrong using our wording and possibly how they can maneuver around the obstacle.

Exceptions vs Errors

I know I keep babbling about exceptions and errors, but what in the heck are they and how are they different you might ask. Well, exceptions generally deal with small little issues that you would probably like to handle. For example, maybe you do not exactly know the type of the variable, but you would definitely like to do something with it. The differences in doing things with numbers and strings are pretty different. So, you might set up something like this:

var1 = '1'
    var1 = var1 + 1 # since var1 is a string, it cannot be added to the number 1
    print(var1, " is not a number") #so we execute this

Awesome! We totally caught the exception that python gave us. We simply put the code we wanted to execute under the try block. However, if an exception occurred (adding a string to and integer is an exception) we told Python to do everything in the except block.

So, what are errors? Bad news, that’s what they are. You normally do not want to handle errors, unless you are doing some dangerous things. When an error is generated, it typically means Python is blowing up the ship, Obviously, if the ship is blown up, we should jump ship and get out of the program.

Also, you might have noticed that the print() takes two arguments in this example. Well, it can take as many arguments as you want to give it. print() will keep on printing all of your arguments with a space in between them.

Elegant Error Handling

Let’s face it our try/except above, doesn’t do a whole lot for the usability of the program. Basically, if it messes up it just tells our users what is wrong. What is the point in that? We should attempt to handle our exceptions in a manner that helps the program to keep moving on. A better alternative would be something like this:

var1 = '1'
    var2 = var1 + 1 # since var1 is a string, it cannot be added to the number 1
    var2 = int(var1) + 1

Ah, much better. In this example, we use our simple except to catch an exception. But, if you run the example, you will see something much more awesome happening. We actually catch the exception, and tell python, “Well, try casting it to an integer before adding”, where Python faithfully obeys. As the end result, Python prints out the number 2 and the user is none the wiser that the program had a small hiccup.

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Share on StumbleUpon
Digg this
Tweet about this on Twitter
Share on Reddit

Leave a Comment

  1. I cant seem to get this example to work in Python 3.3
    i get a SynthaxError: Invalid synthax on the "except:"

  2. Didn’t work here but i did run it in python2.7.5 shell and i got to work just fine after a couple of syntax errors plus me being a newbie.

  3. Ok, for those of you who are having problems with the ‘except’, the issue may likely to be that you didn’t hit backspace after the line ‘var1 = var1 + 1’ (in IDLE). So your code look some like this:

    var1 = var1 + 1

    Where the code breaks here. So I think what the problem is that python still thinks that the ‘except:’ part belongs to the ‘try:’ enclosure, which is an incorrect syntax.

    To resolve this issue, when you start the new line to enter ‘except:’, make sure that you hit backspace once to get the text to begin at start of the line.

    Hope this helps, as this was how I resolved this issue myself.

  4. I know I keep babbling about exceptions and errors, but what in the heck are they and how are the different you might ask.
    Typo: Should Read
    I know I keep babbling about exceptions and errors, but what in the heck are they and how are they different you might ask.

  5. I’ve modified the second example to let it handles other types, but it doesn’t looks elegant enough, is there a more concise way I can get the same result? thanks.

    >>> def fun(a):
    a = int(a) + 1
    print(a, "is ", type(a), "now , please input a number")

  6. hi i cant run the second one in my python 3.4.2 shell
    it run here but in my i get SyntaxError: invalid syntax
    some help?
    i try

    >>> var1=’1′
    >>> try:
    var2 = var1 + 1
    var2 = int(var1) + 1

  7. find the answer!
    to do it, you need to do it in 3 commends.
    first is var1=”1″. hit the enter.
    then try:
    hit the enter again and then make the print(var2) go alone

  8. The try:except is very useful in cases where you do not want the program to stop after a possible error, not necesarily in your code but as a return value, for example in a failed network connection, you may ask the user if he wants to retry to loop back to that routine, or in database handling when for some reason you get back an error from the db, so you cancel or try another option, etc. So in fact it is used for programing sequencing more than detecting possible programing errors. It is almost like a “What if” or “In case of” over possible but unpredictable events.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.