CS50P - Lecture 3 - Exceptions
Table of Contents
Introduction
This tutorial explores error handling in Python, focusing on exceptions. Understanding how to handle exceptions is crucial for writing robust programs that can gracefully manage errors and provide meaningful feedback to users. We will cover common types of errors, how to use try-except blocks, and how to create user-friendly input functions.
Chapter 1: Understanding Exceptions
- Exceptions in Python refer to issues that arise in your code during execution.
- Common types of errors include:
- SyntaxError: Occurs when the code violates Python's syntax rules.
- ValueError: Happens when a function receives an argument of the right type but an inappropriate value.
- NameError: Raised when a variable is referenced before it has been assigned a value.
Practical Advice
- Always check for syntax errors first, as they must be fixed before your code can run.
- Use defensive programming to handle unexpected user input and avoid crashes.
Chapter 2: Handling Syntax Errors
- Open a Python file in your IDE (e.g., VS Code).
- Write simple code, such as:
print("Hello, World")
- Intentionally introduce a syntax error by omitting a quotation mark:
print("Hello, World
- Run the code. You'll see a
SyntaxError
indicating where the problem lies. - Fix the error by ensuring all strings are properly closed.
Key Takeaway
- Syntax errors must be resolved directly in your code and cannot be ignored.
Chapter 3: Handling Value Errors
- Create a new Python file,
number.py
, and write the following code:x = int(input("What's x? ")) print(f"x is {x}")
- Run the code and provide valid integers. It will work as expected.
- Test the program with a string input (e.g., "cat"):
- You will encounter a
ValueError
indicating the input cannot be converted to an integer.
- You will encounter a
Implementing Try-Except
- Modify the code to handle the
ValueError
:while True: try: x = int(input("What's x? ")) break except ValueError: print("x is not an integer") print(f"x is {x}")
- This code loops until valid input is received, catching
ValueError
and informing the user.
Chapter 4: Using Else with Try-Except
- Enhance your error handling with an
else
clause:while True: try: x = int(input("What's x? ")) except ValueError: print("x is not an integer") else: break print(f"x is {x}")
- The
else
block executes only if no exceptions were raised in thetry
block.
Chapter 5: Creating a Custom Input Function
- Define a reusable function
get_int
:def get_int(prompt): while True: try: return int(input(prompt)) except ValueError: print("Input is not a valid integer")
- Use the function in your main code:
x = get_int("What's x? ") print(f"x is {x}")
Benefits of the Function
- The
get_int
function can be reused throughout your program for any integer input, enhancing code clarity and maintainability.
Chapter 6: Improving User Experience
- To make your program friendlier, consider using the
pass
statement in your exception handling:while True: try: x = int(input("What's x? ")) break except ValueError: pass # Do nothing, just keep asking print(f"x is {x}")
- This approach keeps prompting the user without cluttering the output with error messages.
Conclusion
In this tutorial, we've covered the fundamentals of exception handling in Python, including common error types, the use of try-except blocks, and creating user-friendly input functions. Understanding how to handle exceptions not only improves program reliability but also enhances user experience. As you continue your Python journey, practice implementing these concepts in various ways to build robust applications.