1. Introduction: Why Do We Need Custom Exceptions?
In Python programming, various types of runtime exceptions can occur while code is running, which we must handle properly. Furthermore, developers can actively raise exceptions within their code using the raise keyword.
However, situations frequently arise in real-world applications where you need to signal an error that does not fit into Python's built-in default exceptions (such as ValueError or ZeroDivisionError). In these scenarios:
- You want the error to carry a highly descriptive name that immediately communicates the exact business or domain failure.
- Python provides the flexibility to define your own custom exceptions tailored to your application's specific logic.
2. How to Define a Custom Exception in Python
To create a custom exception, you define a class for that exception:
- Inheriting from the Exception class: Whenever you create a custom exception class, you must inherit it from Python's base
Exception class.
- Inherited functionality: By placing
Exception inside parentheses when declaring your class (class CustomError(Exception):), your custom class automatically inherits all the built-in behaviors, message formatting, and traceback mechanisms of Python's exception system.
3. Step-by-Step Implementation: The InvalidAgeError Class
Step 1: Creating the Custom Exception Class
Suppose you are validating user-submitted age data and want a dedicated error indicating that the submitted age is invalid. You define an InvalidAgeError class that inherits from Exception:
# Defining a custom exception class inheriting from the base Exception class
class InvalidAgeError(Exception):
pass
When this cell executes, Python compiles the InvalidAgeError blueprint, endowing it with full exception capabilities.
Step 2: Raising the Custom Exception
When prompting a user for input, if the user enters a negative value (for example, -7), you can explicitly trigger your custom exception using the raise keyword:
# Taking age input from the user
age = int(input("Enter your age: "))
# Inspecting the input for invalid negative values
if age < 0:
# Raising our custom exception with an explanatory message and the input value
raise InvalidAgeError(f"Age cannot be negative. Entered age: {age}")
Output When an Invalid Value Is Entered
If a user inputs a negative number (such as -7), Python stops execution and displays the custom exception:
---------------------------------------------------------------------------
InvalidAgeError Traceback (most recent call last)
Cell In, line 6
3 age = int(input("Enter your age: "))
4
5 if age < 0:
----> 6 raise InvalidAgeError(f"Age cannot be negative. Entered age: {age}")
InvalidAgeError: Age cannot be negative. Entered age: -7
Python generates an exception whose type is explicitly InvalidAgeError, displaying the custom error message and the faulty input value.
4. Handling Custom Exceptions with try...except
Custom exceptions are handled in the exact same way as built-in default exceptions:
- Place the suspect code inside a
try block.
- Catch the specific custom class using an
except InvalidAgeError: block.
try:
# User input that could trigger a negative value
age = int(input("Enter your age: "))
if age < 0:
raise InvalidAgeError(f"Age cannot be negative. Entered age: {age}")
print(f"Valid age recorded: {age}")
# Catching and handling our custom exception cleanly
except InvalidAgeError as error:
print("Handled Exception:", error)
Execution and Output Walkthrough
- If the user enters -7, the
InvalidAgeError is raised.
- The
except InvalidAgeError: block intercepts the exception immediately.
- Instead of displaying a system crash or traceback, it prints:
Handled Exception: Age cannot be negative. Entered age: -7
- The application recovers smoothly and continues executing.
5. Conclusion of the Python Core Track & Next Steps
Mastering custom exceptions completes the Exception Handling module and foundational Python programming track.
- Recommended practice projects: Before moving forward, you can consolidate your knowledge of classes, functions, and exception handling by building comprehensive real-world management systems:
- A Student Management System for a school, college, or university.
- A Car Showroom Management System.
- A custom Business Management System modeling a family or workplace enterprise.
- Next chapter preview: The course transitions into Data Science, where you will learn techniques for handling large volumes of client datasets and extracting meaningful insights from data.