Home » Tutorials » Python » Exceptions

Exceptions

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:

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

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:

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

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.



Link/cite this page

If you use any of the content on this page in your own work, please use the code below to cite this page as the source of the content.

  • Stewart, Suzy. "Exceptions". After Hours Programming. Accessed on March 16, 2024. https://www.afterhoursprogramming.com/tutorial/python/exceptions/.

  • Stewart, Suzy. "Exceptions". After Hours Programming, https://www.afterhoursprogramming.com/tutorial/python/exceptions/. Accessed 16 March, 2024.

  • Stewart, Suzy. Exceptions. After Hours Programming. Retrieved from https://www.afterhoursprogramming.com/tutorial/python/exceptions/.



22 thoughts on “Exceptions”

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

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

  3. 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
    except:
    var2 = int(var1) + 1
    print(var2)

  4. 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):
    try:
    a+=1
    print(a)
    except:
    try:
    a = int(a) + 1
    print(a)
    except:
    print(a, "is ", type(a), "now , please input a number")

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

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

    try:
    var1 = var1 + 1
    except:

    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.

Leave a Comment

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