Introduction
In this lab, we will dive into the world of Python custom exceptions using a fantasy kingdom scenario. The kingdom is under threat from a menacing dragon, and a brave dragon knight has been called upon to defend the kingdom. However, the knight encounters various challenges during this mission, emphasizing the need for customized exception handling in Python.
Custom Exception Creation
In this step, we will create a custom exception class to handle specific scenarios when the dragon knight faces obstacles.
- Open a file named
custom_exceptions.pyin the/home/labex/projectdirectory.
## custom_exceptions.py
## Custom exception class for handling dragon-related errors
class DragonError(Exception):
def __init__(self, message):
super().__init__(message + " - Beware of the dragon!")
After saving the file, you would now have custom exceptions ready to be used.
Using Custom Exception
Now, let's see how our dragon knight can utilize the custom exception to handle an encounter with the dragon.
- Open a file named
dragon_encounter.pyin the/home/labex/projectdirectory.
## dragon_encounter.py
from custom_exceptions import DragonError
def brave_encounter():
try:
## Simulating an encounter with the dragon
raise DragonError("Error in dragon's lair!")
except DragonError as e:
print(e)
brave_encounter()
Run the script:
python dragon_encounter.py
The information below should be displayed on your terminal:
Error in dragon's lair! - Beware of the dragon!
Summary
In this lab, we have designed a scenario involving a fantasy kingdom and a dragon knight to demonstrate the usage of custom exceptions in Python. By creating a custom exception class and using it in a simulated encounter with a dragon, you can understand the practical implementation of custom exceptions and their significance in handling specific error conditions.



