Python Catching Exceptions

PythonPythonBeginner
Practice Now

Introduction

In the enigmatic depths of the Whispering Woods, under the silver cloak of a moonlit night, there was a rumor among the novice sorcerers that a Magic Forest Soul Mentor had appeared. This elusive guide was said to possess the knowledge of Python, the serpentine language that could control the very fabric of code. To find the Mentor was to learn the ancient arts of catching exceptions—a way to enchant one's code to handle the unpredictable spells of error without crashing the magic itself.

One night, you find yourself standing before an ancient oak, its leaves shimmering with an ethereal glow. It is here, in the heart of the forest, where you will learn the Mentor's secrets. Your goal is to master the arcane art of catching exceptions in Python, ensuring that your incantations remain unbroken, even when the unexpected occurs.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/ErrorandExceptionHandlingGroup(["`Error and Exception Handling`"]) python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("`Catching Exceptions`") subgraph Lab Skills python/catching_exceptions -.-> lab-271525{{"`Python Catching Exceptions`"}} end

Identifying Potential Curses

In this step, you’ll learn to identify the potential spots where curses (errors) may occur in your Python incantations (code). Let's begin by crafting a simple spell that can sometimes go awry. We'll create a potion mixing script that will attempt to divide potions into smaller vials, but as any wise sorcerer knows, one must never divide by zero.

Open a file named potion_dividing.py within ~/project and add the following code:

def divide_potions(total_potions, vial_count):
    return total_potions / vial_count

## Attempt to divide 10 potions into 2 vials
print(divide_potions(10, 2))

Run your code in the terminal using the command:

python ~/project/potion_dividing.py

You should see the output:

5.0

It indicates the successful division of potions.

Now, modify the potion_dividing.py script to include a risky spell case.

print(divide_potions(10, 0))  ## This incantation is dangerous and should be handled!

You should see the output:

Traceback (most recent call last):
  File "/home/labex/project/potion_dividing.py", line 6, in <module>
    print(divide_potions(10, 0))
  File "/home/labex/project/potion_dividing.py", line 2, in divide_potions
    return total_potions / vial_count
ZeroDivisionError: division by zero

Executing the improved script will show you the cursed exception that you need to catch. In this lab, we'll learn to handle such cases gracefully.

Crafting a Protective Spell

Having experienced the curse of dividing by zero, it's time to craft a protective spell using the try and except clauses. Update the potion_dividing.py script to include a safeguard against such calamitous outcomes.

def divide_potions(total_potions, vial_count):
    try:
        return total_potions / vial_count
    except ZeroDivisionError:
        return "A sorcerer never divides by zero!"

## Attempt to divide potions safely
print(divide_potions(10, 2))
print(divide_potions(10, 0))  ## This should no longer cause a curse

Run the improved script again in your terminal using:

python ~/project/potion_dividing.py

Your code should now handle the exception gracefully, and instead of an error, it will print out a warning message:

5.0
A sorcerer never divides by zero!

Summary

In this lab, we traversed the shadowy realms of Python exceptions within a magical forest setting. We explored how to identify potential errors and how to conjure protective spells (try/except blocks) to safeguard our code against unexpected calamities without disrupting the incantation flow.

By the end of our journey, we have not only encountered the ZeroDivisionError but also mastered the technique to avert its chaos, making our code more robust and less prone to disruption by the forces of chaos.

As you continue your adventures in coding, remember the words of the Magic Forest Soul Mentor: "A wise sorcerer always expects the unexpected and shields the spell with a protective clause."

Other Python Tutorials you may like