Course Content
Python Advanced Concepts
Python Advanced Concepts
Raising Exceptions
This chapter dives into how and when to raise exceptions, and how you can create custom exceptions to handle specific situations more gracefully in your applications.
How and When to Raise Exceptions
Exceptions in Python should be raised to signal that an error condition has occurred, making it impossible for a function or method to perform its intended task. This is especially useful in situations where simply returning a None
or a similar value could be ambiguous and might not adequately convey that an error has occurred.
Raising a Standard Exception
To raise an exception in Python, you use the raise statement. Here's a simple example:
def calculate_age(birth_year): import datetime current_year = datetime.datetime.now().year age = curren_year - birth_year if age < 0: raise ValueError("The birth year cannot be in the future") return age calculate_age(2034)
In this example, a ValueError is raised if the birth_year
is greater than the current year, indicating that the provided birth year is invalid.
Creating Custom Exceptions
While Python's built-in exceptions cover many different scenarios, sometimes you may need to define your own exceptions to clearly express an error condition specific to your domain.
Defining Custom Exceptions
Custom exceptions are typically derived from the built-in Exception class or one of its subclasses. Here's how you can define a custom exception:
class RegistrationError(Exception): """Base class for all registration-related exceptions.""" pass class UsernameTooShort(RegistrationError): """Raised when the username is too short.""" pass class PasswordTooWeak(RegistrationError): """Raised when the password is too weak.""" pass
Hope you remember the inheritance concept from the OOP 😉
Here's a practical example of how custom exceptions are used. Don't worry about the else
and as
keywords in the example; we'll cover those in the next chapter.
# Custom exceptions class RegistrationError(Exception): pass class UsernameTooShort(RegistrationError): pass class PasswordTooWeak(RegistrationError): pass # Functions to validate registration def validate_username(username): if len(username) < 6: raise UsernameTooShort("Username must be at least 6 characters long") def validate_password(password): if len(password) < 8: raise PasswordTooWeak("Password must be at least 8 characters long") def register_user(username, password): try: validate_username(username) validate_password(password) except RegistrationError as error: print(f"Registration failed: {error}") else: print("User registered successfully!") # Test the registration function register_user("john", "123") # This should fail
Thanks for your feedback!