Skip to Content

Advertisement

You (Level 0)
0% Complete
Last Badge Earned
None

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.

For a more tangible and better look into the Python language, consider reading the following book. It's an excellent read.

Your code will execute in this window.



Let's explore some more tutorials or topics!

Next Tutorial Previous Tutorial

Advertisement

If you enjoyed this resource, support me by sharing this page with others.

Comment on

Show Comments
  • User

    Foro5 March 28, 2015, 7:20 a.m.

    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.

  • User

    isaac Dec. 19, 2014, 6:30 p.m.

    it tells me I have invalid syntax at the last line when everything is going well, what are your guys' answers?

  • User

    Barak Dec. 9, 2014, 6:38 p.m.

    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

  • User

    Barak Dec. 9, 2014, 2:33 p.m.

    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)

  • User

    Eleanor Oct. 22, 2014, 1:41 p.m.

    this is amazing

  • User

    DHDDIY June 22, 2014, 7:23 p.m.

    take the 1 out of quotation code executes fine

  • User

    miles tone April 18, 2014, 9:52 p.m.

    the code in example number 2, produces the following error, '1 undefined'

  • User

    ZhongSIran Feb. 25, 2014, 6:13 a.m.

    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")

  • User

    Satya Jan. 26, 2014, 11:25 p.m.

    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.

  • User

    Jialu Jan. 15, 2014, 3:05 p.m.

    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.

  • User

    Ruksun Jan. 4, 2014, 6:36 a.m.

    What is that I'm doing wrong! I couldn't make both of the examples run

  • User

    Ruben Nov. 4, 2013, 9:12 a.m.

    I have not been able to complete example 1 on Python 3.3.2 Shell. I keep getting syntax errors after typing in: except:

  • User

    Ruben Nov. 4, 2013, 9:10 a.m.

    I have not been able to complete example 1 on Python 3.3.2 Shell. I keep getting syntax errors after typing in: except:

  • User

    steve Oct. 10, 2013, 8:46 p.m.

    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.

  • User

    O _ o Sept. 20, 2013, 8:31 a.m.

    neither of the examples' codes work either in the python command line or in your test code section

  • User

    Rebarakaz Sept. 14, 2013, 7:46 a.m.

    Me to got a SyntaxError: invalid syntax after "except:" I'm using IDLE 3.3.2 on Windows 7 64-bit.

  • User

    Rob MacKay July 25, 2013, 9:04 a.m.

    Typo: "We totally caught the caught the exception" :D

  • User

    Shane Guignard July 9, 2013, 6:01 a.m.

    Wasn't working in terminal, works fine in the module. Sorry for my noobness.

  • User

    Shane Guignard July 4, 2013, 10:03 a.m.

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

  • User

    Dan C May 24, 2013, 12:47 p.m.

    Like the analogy of the ship!

  • User

    Jared Drake March 15, 2013, 9:01 a.m.

    @Brian Nelson Strings can be created using single or double quotes.

  • User

    Jared Drake Feb. 11, 2013, 5:26 p.m.

    @Robert T Excellent point! I must have been rather tired on that example. It is correct now.



Advertisement