top of page
Writer's pictureRevanth Reddy Tondapu

Part 24: Crafting Custom Exceptions in Python: A Simple Guide for Young Coders


Custom Exceptions in Python
Custom Exceptions in Python

Hello young coders! Welcome to a fun and exciting journey through the world of Python programming. Today, we’re going to learn about a special topic: creating custom exceptions. This might sound a bit complex, but don't worry, we'll break it down together and make it super easy to understand!


Why Do We Need Custom Exceptions?

Imagine you're playing a game where you need to enter your age to proceed. If you enter a negative number, the game should tell you that your age can't be negative and ask you to try again. This is where custom exceptions come in handy. They allow us to create specific error messages for particular situations in our programs.


Basic Exception Handling

Before we dive into custom exceptions, let’s quickly recap basic exception handling in Python.

Example: Handling Division by Zero

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Oops! You can't divide by zero.")
finally:
    print("This block always runs.")

In this example:

  • The try block contains code that might cause an error.

  • The except block catches and handles the error.

  • The finally block runs no matter what.


Creating Custom Exceptions

Now, let’s create our own custom exception. We’ll use it to handle a situation where someone enters an invalid age.

Step-by-Step Guide to Custom Exceptions

  1. Define a Custom Exception Class: Create a new class that inherits from Python’s built-in Exception class.

  2. Raise the Exception: Use the raise keyword to trigger the custom exception.

  3. Handle the Exception: Use a try block to catch and handle the custom exception.

Example: Custom Exception for Invalid Age

Let's create a custom exception to handle invalid ages.

# Step 1: Define the custom exception class
class InvalidAgeError(Exception):
    def __init__(self, message):
        self.message = message

# Step 2: Function to check age
def check_age(age):
    if age < 0:
        raise InvalidAgeError("Age cannot be negative!")  # Raise the custom exception
    else:
        print("Valid age")

# Step 3: Handle the custom exception
try:
    check_age(-1)  # Try with an invalid age
except InvalidAgeError as e:
    print(f"Error: {e.message}")
finally:
    print("Age check complete.")

Explanation

  • Custom Exception Class: We create a class InvalidAgeError that extends the built-in Exception class. This class takes a message as a parameter.

  • check_age Function: This function checks if the age is valid. If the age is negative, it raises our custom exception.

  • Handling the Exception: We use a try-except block to catch and handle the InvalidAgeError.


Why Use Custom Exceptions?

Custom exceptions help make your code clearer and more specific. Instead of using generic error messages, you can give detailed messages that make it easier to understand what went wrong.

Example: Custom Exception for Age Range

Let’s create another custom exception for handling ages that are too high.

class AgeTooHighError(Exception):
    def __init__(self, message):
        self.message = message

def check_age_range(age):
    if age > 120:
        raise AgeTooHighError("Age cannot be more than 120!")  # Raise the custom exception
    elif age < 0:
        raise InvalidAgeError("Age cannot be negative!")  # Reusing previous custom exception
    else:
        print("Valid age")

try:
    check_age_range(130)  # Try with an age that's too high
except InvalidAgeError as e:
    print(f"Error: {e.message}")
except AgeTooHighError as e:
    print(f"Error: {e.message}")
finally:
    print("Age range check complete.")

Explanation

  • We define a new custom exception AgeTooHighError for ages greater than 120.

  • The check_age_range function now handles both the InvalidAgeError and AgeTooHighError exceptions.

  • The try-except block catches and handles both types of custom exceptions.


Conclusion

Creating custom exceptions in Python helps make your programs more robust and user-friendly. By providing specific error messages, you can guide users to correct their mistakes easily. Remember, practice makes perfect, so try creating your own custom exceptions for different scenarios!

Stay tuned for more fun and advanced Python topics. Keep coding, keep learning, and don’t forget to share your newfound knowledge with your friends!

If you enjoyed this post, make sure to share it and subscribe for more awesome Python tips and tricks. Happy coding!

6 views0 comments

Recent Posts

See All

Comments


bottom of page