21 Decoding Ancient Texts: The Art of Error Handling
In our previous lessons, we learned powerful string methods for manipulating text. But what happens when our spells don’t work exactly as planned? Today, we’ll learn about error handling using Python’s try
and except
statements. Just as a skilled scribe must know how to handle damaged or illegible texts, a Python programmer must know how to handle potential errors gracefully.
21.1 What are Errors in Python?
When something goes wrong in our code, Python raises an error (also called an exception). Let’s see some common errors that can occur when working with strings:
# Trying to access a character beyond the string length
= "Magic"
scroll print("Attempting to access the 10th character...")
= scroll[10] # This raises an IndexError last_letter
If you run this code, Python will stop your program and show:
IndexError: string index out of range
Similarly, when converting strings to numbers:
# Trying to convert non-numeric text to a number
= "many"
treasure_count print("Attempting to convert 'many' to a number...")
= int(treasure_count) # This raises a ValueError number
Python will show:
ValueError: invalid literal for int() with base 10: 'many'
21.2 The Try/Except Structure
Instead of letting these errors crash our program, we can handle them gracefully using try
and except
. Here’s the basic structure:
try:
# Code that might raise an error
except:
# Code to handle the error
Let’s make our previous examples better:
= "Magic"
scroll print("Attempting to access the 10th character...")
try:
= scroll[10]
last_letter print("The 10th letter is:", last_letter)
except:
print("The scroll text isn't long enough!")
print("The program continues running!")
This will output:
Attempting to access the 10th character...
The scroll text isn't long enough!
The program continues running!
21.3 Handling Specific Error Types
We can catch specific types of errors by naming them in the except
statement. This is like having different solutions for different problems:
# Let's handle string-to-number conversion errors
= "many"
treasure_count print("\nAttempting to count treasures...")
try:
= int(treasure_count)
number print("You have", number, "treasures!")
except ValueError:
print("'many' is not a valid number of treasures!")
print("\nLet's try with a real number...")
= "5"
treasure_count try:
= int(treasure_count)
number print("You have", number, "treasures!")
except ValueError:
print("That's not a valid number of treasures!")
This will output:
Attempting to count treasures...
'many' is not a valid number of treasures!
Let's try with a real number...
You have 5 treasures!
21.4 Multiple Except Blocks
Sometimes different things can go wrong. We can handle different types of errors differently:
= "Merlin"
ancient_text print("Let's try some risky text operations...")
try:
# Try to convert "two" to a number (this will fail)
= int("two")
position # This line won't run because of the previous error
= ancient_text[position]
letter print(f"The letter is: {letter}")
except ValueError:
print("'two' is not a valid position number!")
except IndexError:
print("That position is beyond the text length!")
21.5 Using Try/Except with String Methods
Let’s apply error handling to some of the string methods we learned earlier:
= None # Imagine this came from somewhere else
mysterious_text print("\nTrying to clean up mysterious text...")
try:
= mysterious_text.strip()
cleaned_text = cleaned_text.upper()
uppercase_text print(f"The text says: {uppercase_text}")
except AttributeError:
print("Cannot read the mysterious text!")
print("\nLet's try with actual text...")
= " ancient secrets "
mysterious_text try:
= mysterious_text.strip()
cleaned_text = cleaned_text.upper()
uppercase_text print(f"The text says: {uppercase_text}")
except AttributeError:
print("Cannot read the mysterious text!")
21.6 Practice Time: Error Handling Quests
Now it’s your turn to practice error handling. Try these challenges:
- Create code that tries to convert “one hundred” to a number and handles the error:
= "one hundred"
magic_number try:
= int(magic_number)
result print(f"The number is: {result}")
except ValueError:
print("That's not a proper number!")
- Write code that tries to access different positions in a string:
= "Abracadabra"
magic_word print("\nTrying position 15...")
try:
= magic_word[15]
letter print(f"The letter is: {letter}")
except IndexError:
print("That position doesn't exist in the word!")
print("\nTrying position 0...")
try:
= magic_word[0]
letter print(f"The letter is: {letter}")
except IndexError:
print("That position doesn't exist in the word!")
- Try using string methods on different types of values:
= None
text print("\nTrying to use string methods...")
try:
= text.strip()
clean_text print(f"Cleaned text: {clean_text}")
except AttributeError:
print("Cannot use string methods on this value!")
21.7 Common Bugs to Watch Out For
As you practice error handling, be wary of these common pitfalls:
Catching all errors: Using bare
except:
without specifying an error type can hide bugs. It’s better to catch specific errors.Order of except blocks: When catching multiple error types, remember that Python checks them in order. Put more specific error types before more general ones.
Hiding important errors: Not all errors should be caught. Sometimes it’s better to let the program show the error than to hide serious problems.
Missing the error message: When an error occurs, Python tries to tell you what went wrong. Pay attention to these messages!
21.8 Conclusion and Further Resources
Congratulations! You’ve learned how to handle errors gracefully in your code. This skill will help you write programs that can deal with unexpected situations without crashing.
To learn more about error handling in Python, check out these resources:
- Python’s official documentation on Errors and Exceptions
- Real Python’s Python Exceptions Guide
- W3Schools Python Try Except
Remember, handling errors well is just as important as writing the code in the first place. Keep practicing these techniques, and your programs will become more reliable and user-friendly!