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
scroll = "Magic"
print("Attempting to access the 10th character...")
last_letter = scroll[10]   # This raises an IndexError

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
treasure_count = "many"
print("Attempting to convert 'many' to a number...")
number = int(treasure_count)   # This raises a ValueError

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:

scroll = "Magic"
print("Attempting to access the 10th character...")
try:
    last_letter = scroll[10]
    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
treasure_count = "many"
print("\nAttempting to count treasures...")
try:
    number = int(treasure_count)
    print("You have", number, "treasures!")
except ValueError:
    print("'many' is not a valid number of treasures!")

print("\nLet's try with a real number...")
treasure_count = "5"
try:
    number = int(treasure_count)
    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:

ancient_text = "Merlin"
print("Let's try some risky text operations...")

try:
    # Try to convert "two" to a number (this will fail)
    position = int("two")
    # This line won't run because of the previous error
    letter = ancient_text[position]
    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:

mysterious_text = None  # Imagine this came from somewhere else
print("\nTrying to clean up mysterious text...")
try:
    cleaned_text = mysterious_text.strip()
    uppercase_text = cleaned_text.upper()
    print(f"The text says: {uppercase_text}")
except AttributeError:
    print("Cannot read the mysterious text!")

print("\nLet's try with actual text...")
mysterious_text = "  ancient secrets  "
try:
    cleaned_text = mysterious_text.strip()
    uppercase_text = cleaned_text.upper()
    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:

  1. Create code that tries to convert “one hundred” to a number and handles the error:
magic_number = "one hundred"
try:
    result = int(magic_number)
    print(f"The number is: {result}")
except ValueError:
    print("That's not a proper number!")
  1. Write code that tries to access different positions in a string:
magic_word = "Abracadabra"
print("\nTrying position 15...")
try:
    letter = magic_word[15]
    print(f"The letter is: {letter}")
except IndexError:
    print("That position doesn't exist in the word!")

print("\nTrying position 0...")
try:
    letter = magic_word[0]
    print(f"The letter is: {letter}")
except IndexError:
    print("That position doesn't exist in the word!")
  1. Try using string methods on different types of values:
text = None
print("\nTrying to use string methods...")
try:
    clean_text = text.strip()
    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:

  1. Catching all errors: Using bare except: without specifying an error type can hide bugs. It’s better to catch specific errors.

  2. 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.

  3. 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.

  4. 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:

  1. Python’s official documentation on Errors and Exceptions
  2. Real Python’s Python Exceptions Guide
  3. 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!