1.9. Errors

Some students thought a quick walkthrough of errors and fixing them would be helpful.

Below, I try to fix a two line program, and you’ll see the most common error types. There are more error types in python, and for more info, I’ll refer you to

When you get to more advanced programming, you’ll sometimes want code running even when it produces an error! The last section below has some pointers on that.

1.9.1. Most common error types

Tip

This website-tutorialsteacher has a nice page listing the most common error types. If you get an error and aren’t sure what it means, refer to this link as a starting point.

1.9.1.1. SyntaxError

Means there is something wrong with the way your program is written. This often means you included or excluded punctuation that does/does not belong.

if True
print("hi""+2+name)
  File "C:\Users\DONSLA~1\AppData\Local\Temp/ipykernel_4624/2052770430.py", line 1
    if True
           ^
SyntaxError: invalid syntax

Let’s fix that by adding a colon.

if True: # <-- fix
print("hi ""+2+name)
  File "C:\Users\DONSLA~1\AppData\Local\Temp/ipykernel_4624/2572534488.py", line 2
    print("hi ""+2+name)
    ^
IndentationError: expected an indented block

1.9.1.2. IndentationError

Is pretty self-explanatory but common, especially when you’re writing code with multiple layers of for, if, def, try, etc…

Let’s fix that by adding an indent inside the if statement:

if True: 
    print("hi ""+2+name)
  File "C:\Users\DONSLA~1\AppData\Local\Temp/ipykernel_4624/702078298.py", line 2
    print("hi ""+2+name)
                        ^
SyntaxError: EOL while scanning string literal

Drats! Another SyntaxError! Something is wrong with this line. I’m going to work from left to right. First, the quotation marks are unbalanced. We can fix that.

if True: 
    print("hi "+2+name)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\Users\DONSLA~1\AppData\Local\Temp/ipykernel_4624/3629975047.py in <module>
      1 if True:
----> 2     print("hi "+2+name)

TypeError: can only concatenate str (not "int") to str

1.9.1.3. TypeError

I tried to add a number (int) to a string. Python doesn’t allow that.

if True: 
    print("hi "+name)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
C:\Users\DONSLA~1\AppData\Local\Temp/ipykernel_4624/1555074345.py in <module>
      1 if True:
----> 2     print("hi "+name)

NameError: name 'name' is not defined

1.9.1.4. NameError

Python interpreter sees a word it does not recognize. You need to define the variable before it is used!

name = "Jack"
if True: 
    print("hi "+name)
hi Jack

1.9.2. Handling errors

Here is the syntax with pseudocode for try-except blocks, borrowed from an answer on SO. You must include at least one except block for any try block.

try:
    try_this(whatever)
    
except SomeException: 
    # this block runs only if the code inside "try" returns SomeException
    
    handle_this()
    
except DiffException as the_exception:  
    # you can handle multiple exceptions...
    # this block runs only if the code inside "try" returns DiffException
    # you can "name" your exception type, here "as the_exception" does that
    
    handle_this_one(the_exception)
    
else: 
    # the else block only runs if no exceptions occur
    
    do_something_if_no_exceptions()

finally:
    # this block will execute no matter what, even if no exception,
    
    always_does_this()

Warning

Avoid bare except: clauses. The idea is to handle expected errors.

1.9.2.1. References

I’d read through these pages for some walkthroughs and discussions of try-except:

  1. This StackOverflow discussion has some really good answers talking about the whys and whens of try-except in python.

  2. Tutorialsteacher

  3. Official Python docs