Python Raising Exceptions

PythonPythonBeginner
Practice Now

Introduction

Welcome to the Arcane Academy of Exceptional Coding—a prestigious institution where only the most capable coding wizards gather to sharpen their craft. You are a young wizard who has recently joined the academy and the ever-challenging world of magical algorithms and complex incantations.

Your journey begins under the guidance of Master Pytho, a renowned Competitive Spellcasting Coach known throughout the magical realms for his exceptional problem-solving skills and vast knowledge of Pythonic sorcery. In the academy, every wizard must learn the art of spellcasting, but what makes a wizard truly powerful is the ability to anticipate and manage the unexpected.

Today, Master Pytho will teach you the ancient art of Raising Exceptions—a fundamental skill for any aspiring wizard that allows them to control the flow of magic (code) and create fail-safes against unforeseen errors that may arise during spellcasting (programming).

The goal of this Lab is to empower you to write robust Python code that can handle and raise exceptions properly, ensuring your spells (programs) are not only potent but also resilient and secure. Prepare yourself, for you are about to embark on an enchanted journey through the arcane world of Python Raising Exceptions!


Skills Graph

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

Understanding the Basics of Exceptions

In this step, you will learn about the basics of exceptions in Python. An exception in Python is like an unplanned event that disrupts the flow of a spellcasting sequence. When Python encounters an error, it stops the current process and passes it along the call stack until it is handled. If unhandled, the spell (program) crashes, and Python prints an error message.

To simulate a scenario where an exception might occur, you will create a simple Python script that tries to cast a spell (execute a division) that goes awry.

Open a file named spellcasting.py in the ~/project directory with the following content:

## spellcasting.py

def divide_potions(potions, wizards):
    return potions / wizards

## An attempt to divide potions among zero wizards, which will raise an exception.
divide_potions(10, 0)

Run your spellcasting script using the command:

python3 ~/project/spellcasting.py

You will notice that Python raises a ZeroDivisionError. In the next step, you'll learn how to properly handle this exception:

Traceback (most recent call last):
  File "/home/labex/project/spellcasting.py", line 7, in <module>
    divide_potions(10, 0)
  File "/home/labex/project/spellcasting.py", line 4, in divide_potions
    return potions / wizards
ZeroDivisionError: division by zero

Raising Custom Exceptions

It's time to move to a more advanced spellcasting technique—raising your own exceptions. This allows you to create and use custom error messages, making your spells more flexible and controlled.

In this step, you will modify the spellcasting.py script to raise a custom Exception when an incorrect number of wizards is passed to the divide_potions function.

First, modify the divid_potions function in spellcasting.py accordingly:

## spellcasting.py

def divide_potions(potions, wizards):
    if wizards == 0:
        raise Exception("Cannot divide potions among zero wizards!")
    return potions / wizards

## Try to divide potions again with intentional error.
divide_potions(20, 0)

After saving the changes, run your modified script again:

python3 ~/project/spellcasting.py

This time, Python will raise the custom Exception message:

Traceback (most recent call last):
  File "/home/labex/project/spellcasting.py", line 7, in <module>
    divide_potions(20, 0)
  File "/home/labex/project/spellcasting.py", line 3, in divide_potions
    raise Exception("Cannot divide potions among zero wizards!")
Exception: Cannot divide potions among zero wizards!

Handling Exceptions with Try-Except

In this step, you will learn how to handle exceptions gracefully using the try-except block. Ensuring that your spell (program) can recover from errors is a critical skill for a wizard.

Add the try-except block around the divide_potions function call in the spellcasting.py script:

## spellcasting.py

def divide_potions(potions, wizards):
    if wizards == 0:
        raise Exception("Cannot divide potions among zero wizards!")
    return potions / wizards

try:
    ## Try to divide potions and handle potential errors.
    result = divide_potions(30, 0)
    print(f"Each wizard receives {result} potions.")
except Exception as e:
    print(f"Spell failed: {e}")

Run this in the shell:

python3 ~/project/spellcasting.py

Now, when you run the script, instead of crashing, it will print the output:

Spell failed: Cannot divide potions among zero wizards!

Summary

In this lab, we ventured through the bewitching lands of Python Raising Exceptions. We began with an introduction to exceptions by letting one naturally occur, then learned how to craft our own exceptions and messages, and finally wrapped up with the art of handling these exceptions without breaking our spell (program).

You have now mastered the fundamentals of raising and handling exceptions in Python, a skill that will undoubtedly serve you well in your journey as a coding wizard. This not only contributes to the robustness and user-friendliness of your programs but also teaches you to predict and prepare for unexpected behaviors—keeping your spells foolproof and your prowess as a wizard formidable.

May the code be with you, young sorcerer.

Other Python Tutorials you may like