Errors and Exceptions in Python

PythonBeginner
Practice Now

Introduction

In this lab, you will gain a practical understanding of errors and exceptions in Python. We will explore how to identify common syntax errors that prevent code execution, recognize various types of exceptions that occur during runtime, and clearly differentiate between these two fundamental concepts in Python programming.

Through hands-on exercises, you will learn to spot and fix issues like incorrect indentation, missing syntax elements, and other common pitfalls, building a solid foundation for writing robust and error-free Python code.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

Identify Syntax Errors

In this step, we will explore common syntax errors in Python. Syntax errors occur when the code violates the grammatical rules of the language, preventing the interpreter from understanding and executing the code. These errors are detected before the program even starts running.

The necessary file syntax_errors.py has been created for you in the ~/project directory.

First, let's introduce an IndentationError. Open syntax_errors.py from the file explorer on the left side of the WebIDE. Add the following code, which contains incorrect indentation:

for i in range(5):
    print(i)
  print("This line has incorrect indentation")

Save the file. Now, open the integrated terminal and run the script:

python syntax_errors.py

You will see an IndentationError. The Python interpreter expects code blocks (like the one inside a for loop) to have a consistent indentation level.

  File "/home/labex/project/syntax_errors.py", line 3
    print("This line has incorrect indentation")
                                                ^
IndentationError: unindent does not match any outer indentation level

Now, let's fix the indentation but introduce a different SyntaxError. Modify the code in syntax_errors.py to the following. Notice the missing colon (:) at the end of the first line.

for i in range(5)
    print(i)
    print("This line has correct indentation")

Save the file and run it again from the terminal:

python syntax_errors.py

This time, you will get a SyntaxError. The for loop statement in Python requires a colon at the end to signify the beginning of a code block.

  File "/home/labex/project/syntax_errors.py", line 1
    for i in range(5)
                     ^
SyntaxError: expected ':'

Finally, let's correct the colon but introduce another common SyntaxError: an unterminated string. Modify the syntax_errors.py file as follows. The string "hello' starts with a double quote but ends with a single quote.

for i in range(5):
    print("hello')

Save the file and run it:

python syntax_errors.py

You will encounter a SyntaxError because the string was not properly closed with a matching quote.

  File "/home/labex/project/syntax_errors.py", line 2
    print("hello')
          ^
SyntaxError: unterminated string literal (detected at line 2)

These examples illustrate that syntax errors must be fixed before your program can run. Always pay close attention to indentation, required symbols like colons, and matching quotes.

Recognize Common Exceptions

In this step, we will explore common exceptions. Unlike syntax errors, exceptions occur during program execution. The code is syntactically correct, but an error occurs while it is running.

The file common_exceptions.py is ready for you in the ~/project directory.

First, let's cause a ZeroDivisionError. Open common_exceptions.py in the editor and add the following code:

numerator = 10
denominator = 0
result = numerator / denominator
print(result)

Save the file and run it from the terminal:

python common_exceptions.py

The program starts running but stops and displays a ZeroDivisionError. Mathematically, division by zero is undefined, and Python raises this exception to indicate the problem.

Traceback (most recent call last):
  File "/home/labex/project/common_exceptions.py", line 3, in <module>
    result = numerator / denominator
ZeroDivisionError: division by zero

Next, let's trigger a NameError. This happens when you try to use a variable that has not been defined yet. Replace the content of common_exceptions.py with the following:

print(undefined_variable)

Save the file and run it:

python common_exceptions.py

You will get a NameError because the interpreter does not know what undefined_variable refers to.

Traceback (most recent call last):
  File "/home/labex/project/common_exceptions.py", line 1, in <module>
    print(undefined_variable)
NameError: name 'undefined_variable' is not defined

Now, let's see a TypeError. This occurs when you try to perform an operation on an object of an inappropriate type. Replace the content of common_exceptions.py with this code:

print("Hello" + 5)

Save and run the script:

python common_exceptions.py

You will see a TypeError. Python does not allow you to add (+) a string and an integer together directly.

Traceback (most recent call last):
  File "/home/labex/project/common_exceptions.py", line 1, in <module>
    print("Hello" + 5)
TypeError: can only concatenate str (not "int") to str

Finally, let's demonstrate an IndexError. This happens when you try to access an element of a sequence (like a list) using an index that is out of bounds. Replace the content of common_exceptions.py with the following:

my_list = [1, 2, 3]
print(my_list[5])

Save and run the script:

python common_exceptions.py

You will get an IndexError. The list my_list has three items, so its valid indices are 0, 1, and 2. Accessing index 5 is not possible.

Traceback (most recent call last):
  File "/home/labex/project/common_exceptions.py", line 2, in <module>
    print(my_list[5])
IndexError: list index out of range

Understanding these common exceptions is a key part of learning to debug Python code.

Differentiate Between Errors and Exceptions

In this final step, we will clearly distinguish between syntax errors and exceptions. This distinction is fundamental to Python programming and debugging.

Syntax Errors (or Parsing Errors):

  • These are mistakes in the structure of your code that violate Python's rules.
  • The Python interpreter finds these errors before your program begins to run.
  • A program with a syntax error cannot be executed at all.
  • Examples: IndentationError, missing colons, mismatched parentheses or quotes.

Exceptions (or Runtime Errors):

  • These errors occur during the execution of a syntactically correct program.
  • They happen when the program encounters an unexpected situation, like dividing by zero or accessing a non-existent file.
  • If not handled, an exception will cause your program to crash and print a traceback.
  • Examples: ZeroDivisionError, NameError, TypeError, IndexError.

Let's see this in action. Open the file error_vs_exception.py from the file explorer. Add the following code, which contains both a syntax error (a missing colon) and a line that will cause a runtime exception.

## This line has a syntax error (missing colon)
for i in range(5)
    print(i)

## This line will cause an exception (division by zero)
result = 10 / 0
print(result)

Save the file and try to run it:

python error_vs_exception.py

Notice that you immediately get a SyntaxError. The interpreter checks the entire file for correct syntax before running any of it. It finds the missing colon and stops, never even reaching the line with 10 / 0.

  File "/home/labex/project/error_vs_exception.py", line 2
    for i in range(5)
                     ^
SyntaxError: expected ':'

Now, let's fix the syntax error. Add the missing colon to the for loop line in error_vs_exception.py:

## The syntax error is now fixed
for i in range(5):
    print(i)

## This line will cause an exception (division by zero)
result = 10 / 0
print(result)

Save the file and run it again:

python error_vs_exception.py

This time, the program is syntactically correct, so it starts running. The for loop executes and prints the numbers 0 through 4. Then, when the program tries to execute result = 10 / 0, it encounters a runtime problem and raises a ZeroDivisionError, causing the program to crash.

0
1
2
3
4
Traceback (most recent call last):
  File "/home/labex/project/error_vs_exception.py", line 6, in <module>
    result = 10 / 0
ZeroDivisionError: division by zero

This clearly demonstrates that syntax errors prevent execution, while exceptions occur during execution. In future labs, you will learn how to handle exceptions gracefully so they don't crash your program.

Summary

In this lab, you have learned the fundamental difference between errors and exceptions in Python. You started by identifying and fixing common syntax errors, such as IndentationError and SyntaxError from a missing colon, understanding that these prevent a program from running at all.

Next, you explored several common runtime exceptions, including ZeroDivisionError, NameError, TypeError, and IndexError. You saw how these exceptions occur in syntactically correct code when an operation fails during execution. Finally, you solidified your understanding by observing how the Python interpreter handles a file containing both a syntax error and a potential exception, proving that syntax is checked before execution begins. This knowledge provides a crucial foundation for writing and debugging Python applications.