Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Raising Exceptions | Error Handling
Python Advanced Concepts
course content

Conteúdo do Curso

Python Advanced Concepts

Python Advanced Concepts

1. Modules and Imports
2. Error Handling
3. File Handling
4. Pytest Framework
5. Unittest Framework
6. Iterators and Generators

book
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:

123456789
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)
copy

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:

1234567891011
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
copy

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.

123456789101112131415161718192021222324252627282930
# 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
copy

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 2
We're sorry to hear that something went wrong. What happened?
some-alt