Chapter 9: Error Handling and Exceptions
9.3: Raising Exceptions
In Python, exceptions are events that can occur when there is an error or an exceptional condition during the execution of a program. These can be caused by a variety of factors, such as incorrect input or an unexpected event. As we have seen before, Python automatically raises exceptions when it encounters an error.
However, you can also manually raise exceptions in your code by using the raise
statement. This is particularly useful when you want to enforce certain conditions or constraints in your program, such as checking for valid input or ensuring that certain resources are available before executing a piece of code.
To raise an exception, you can use the raise
keyword followed by the exception class or an instance of the exception class you want to raise. This can be helpful in providing additional context for the error, such as specifying the type of error that occurred or providing a custom message to the user. By raising exceptions in your code, you can improve its robustness and make it more reliable, ensuring that it can handle a wide range of inputs and conditions.
Here is the basic syntax for raising an exception:
raise ExceptionClass("Error message")
For example, you can raise a ValueError
exception if you want to enforce that a certain value should be within a specific range:
def validate_age(age):
if age < 0 or age > 150:
raise ValueError("Invalid age: Age must be between 0 and 150")
try:
validate_age(-5)
except ValueError as ve:
print(ve)
In this example, the validate_age
function checks if the given age is within the valid range (0 to 150). If it is not, a ValueError
exception is raised with a custom error message. We then use a try-except block to call the function and handle the exception if it occurs.
When you raise an exception in your code, you are essentially signaling that something has gone wrong and the normal flow of your program cannot continue. This means that the control is transferred to the nearest enclosing try-except block, which is a block of code designed to handle exceptions in a specific way. If there is no such block, the program will terminate, and the error message will be displayed.
But why is it so important to raise exceptions in the first place? Well, doing so can actually help you create more robust and error-resilient code. By detecting and handling errors early on in the code, you can prevent them from causing unexpected behavior or even crashing your program altogether. This can save you time and frustration in the long run, as well as make your code more reliable and easier to maintain.
Exercise 9.3.1: Raising Exceptions for Invalid Input
Title: Validate User Input
Description: Write a function called validate_input
that takes a string as its input and raises a ValueError
exception if the input string contains any special characters (e.g., !
, @
, #
, etc.).
Instructions:
- Create a function
validate_input
that takes a stringinput_str
. - Check if the input string contains any special characters.
- If it does, raise a
ValueError
with a custom error message. - Test the function with valid and invalid inputs using a try-except block.
Solution:
import string
def validate_input(input_str):
if any(char in string.punctuation for char in input_str):
raise ValueError("Invalid input: The input should not contain special characters")
try:
validate_input("HelloWorld!")
except ValueError as ve:
print(ve)
try:
validate_input("HelloWorld")
except ValueError as ve:
print(ve)
Output:
Invalid input: The input should not contain special characters
Exercise 9.3.2: Raising Exceptions for Invalid Passwords
Title: Password Strength Checker
Description: Create a function called validate_password
that checks if a given password is strong. A strong password is defined as having at least 8 characters, containing at least one uppercase letter, one lowercase letter, one digit, and one special character. Raise a ValueError
exception if the password does not meet these criteria.
Instructions:
- Create a function
validate_password
that takes a stringpassword
. - Check if the password meets the criteria for a strong password.
- If it does not, raise a
ValueError
with a custom error message. - Test the function with valid and invalid passwords using a try-except block.
Solution:
import string
def validate_password(password):
if len(password) < 8:
raise ValueError("Invalid password: Password must have at least 8 characters")
if not any(char.isupper() for char in password):
raise ValueError("Invalid password: Password must have at least one uppercase letter")
if not any(char.islower() for char in password):
raise ValueError("Invalid password: Password must have at least one lowercase letter")
if not any(char.isdigit() for char in password):
raise ValueError("Invalid password: Password must have at least one digit")
if not any(char in string.punctuation for char in password):
raise ValueError("Invalid password: Password must have at least one special character")
try:
validate_password("WeakPwd1")
except ValueError as ve:
print(ve)
try:
validate_password("StrongPwd1!")
except ValueError as ve:
print(ve)
Output:
Invalid password: Password must have at least one special character
Exercise 9.3.3: Raising Exceptions for Invalid Email Addresses
Title: Email Validator
Description: Create a function called validate_email
that checks if a given email address is valid. A valid email address should have the following format: <username>@<domain>.<tld>
. Raise a ValueError
exception if the email address does not meet these criteria.
Instructions:
- Create a function
validate_email
that takes a stringemail
. - Check if the email address is valid.
- If it is not, raise a
ValueError
with a custom error message. - Test the function with valid and invalid email addresses using a try-except block.
Solution:
import re
def validate_email(email):
email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not re.match(email_regex, email):
raise ValueError("Invalid email address")
try:
validate_email("invalid_email.com")
except ValueError as ve:
print(ve)
try:
validate_email("valid.email@example.com")
except ValueError as ve:
print(ve)
Output:
Invalid email address
9.3: Raising Exceptions
In Python, exceptions are events that can occur when there is an error or an exceptional condition during the execution of a program. These can be caused by a variety of factors, such as incorrect input or an unexpected event. As we have seen before, Python automatically raises exceptions when it encounters an error.
However, you can also manually raise exceptions in your code by using the raise
statement. This is particularly useful when you want to enforce certain conditions or constraints in your program, such as checking for valid input or ensuring that certain resources are available before executing a piece of code.
To raise an exception, you can use the raise
keyword followed by the exception class or an instance of the exception class you want to raise. This can be helpful in providing additional context for the error, such as specifying the type of error that occurred or providing a custom message to the user. By raising exceptions in your code, you can improve its robustness and make it more reliable, ensuring that it can handle a wide range of inputs and conditions.
Here is the basic syntax for raising an exception:
raise ExceptionClass("Error message")
For example, you can raise a ValueError
exception if you want to enforce that a certain value should be within a specific range:
def validate_age(age):
if age < 0 or age > 150:
raise ValueError("Invalid age: Age must be between 0 and 150")
try:
validate_age(-5)
except ValueError as ve:
print(ve)
In this example, the validate_age
function checks if the given age is within the valid range (0 to 150). If it is not, a ValueError
exception is raised with a custom error message. We then use a try-except block to call the function and handle the exception if it occurs.
When you raise an exception in your code, you are essentially signaling that something has gone wrong and the normal flow of your program cannot continue. This means that the control is transferred to the nearest enclosing try-except block, which is a block of code designed to handle exceptions in a specific way. If there is no such block, the program will terminate, and the error message will be displayed.
But why is it so important to raise exceptions in the first place? Well, doing so can actually help you create more robust and error-resilient code. By detecting and handling errors early on in the code, you can prevent them from causing unexpected behavior or even crashing your program altogether. This can save you time and frustration in the long run, as well as make your code more reliable and easier to maintain.
Exercise 9.3.1: Raising Exceptions for Invalid Input
Title: Validate User Input
Description: Write a function called validate_input
that takes a string as its input and raises a ValueError
exception if the input string contains any special characters (e.g., !
, @
, #
, etc.).
Instructions:
- Create a function
validate_input
that takes a stringinput_str
. - Check if the input string contains any special characters.
- If it does, raise a
ValueError
with a custom error message. - Test the function with valid and invalid inputs using a try-except block.
Solution:
import string
def validate_input(input_str):
if any(char in string.punctuation for char in input_str):
raise ValueError("Invalid input: The input should not contain special characters")
try:
validate_input("HelloWorld!")
except ValueError as ve:
print(ve)
try:
validate_input("HelloWorld")
except ValueError as ve:
print(ve)
Output:
Invalid input: The input should not contain special characters
Exercise 9.3.2: Raising Exceptions for Invalid Passwords
Title: Password Strength Checker
Description: Create a function called validate_password
that checks if a given password is strong. A strong password is defined as having at least 8 characters, containing at least one uppercase letter, one lowercase letter, one digit, and one special character. Raise a ValueError
exception if the password does not meet these criteria.
Instructions:
- Create a function
validate_password
that takes a stringpassword
. - Check if the password meets the criteria for a strong password.
- If it does not, raise a
ValueError
with a custom error message. - Test the function with valid and invalid passwords using a try-except block.
Solution:
import string
def validate_password(password):
if len(password) < 8:
raise ValueError("Invalid password: Password must have at least 8 characters")
if not any(char.isupper() for char in password):
raise ValueError("Invalid password: Password must have at least one uppercase letter")
if not any(char.islower() for char in password):
raise ValueError("Invalid password: Password must have at least one lowercase letter")
if not any(char.isdigit() for char in password):
raise ValueError("Invalid password: Password must have at least one digit")
if not any(char in string.punctuation for char in password):
raise ValueError("Invalid password: Password must have at least one special character")
try:
validate_password("WeakPwd1")
except ValueError as ve:
print(ve)
try:
validate_password("StrongPwd1!")
except ValueError as ve:
print(ve)
Output:
Invalid password: Password must have at least one special character
Exercise 9.3.3: Raising Exceptions for Invalid Email Addresses
Title: Email Validator
Description: Create a function called validate_email
that checks if a given email address is valid. A valid email address should have the following format: <username>@<domain>.<tld>
. Raise a ValueError
exception if the email address does not meet these criteria.
Instructions:
- Create a function
validate_email
that takes a stringemail
. - Check if the email address is valid.
- If it is not, raise a
ValueError
with a custom error message. - Test the function with valid and invalid email addresses using a try-except block.
Solution:
import re
def validate_email(email):
email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not re.match(email_regex, email):
raise ValueError("Invalid email address")
try:
validate_email("invalid_email.com")
except ValueError as ve:
print(ve)
try:
validate_email("valid.email@example.com")
except ValueError as ve:
print(ve)
Output:
Invalid email address
9.3: Raising Exceptions
In Python, exceptions are events that can occur when there is an error or an exceptional condition during the execution of a program. These can be caused by a variety of factors, such as incorrect input or an unexpected event. As we have seen before, Python automatically raises exceptions when it encounters an error.
However, you can also manually raise exceptions in your code by using the raise
statement. This is particularly useful when you want to enforce certain conditions or constraints in your program, such as checking for valid input or ensuring that certain resources are available before executing a piece of code.
To raise an exception, you can use the raise
keyword followed by the exception class or an instance of the exception class you want to raise. This can be helpful in providing additional context for the error, such as specifying the type of error that occurred or providing a custom message to the user. By raising exceptions in your code, you can improve its robustness and make it more reliable, ensuring that it can handle a wide range of inputs and conditions.
Here is the basic syntax for raising an exception:
raise ExceptionClass("Error message")
For example, you can raise a ValueError
exception if you want to enforce that a certain value should be within a specific range:
def validate_age(age):
if age < 0 or age > 150:
raise ValueError("Invalid age: Age must be between 0 and 150")
try:
validate_age(-5)
except ValueError as ve:
print(ve)
In this example, the validate_age
function checks if the given age is within the valid range (0 to 150). If it is not, a ValueError
exception is raised with a custom error message. We then use a try-except block to call the function and handle the exception if it occurs.
When you raise an exception in your code, you are essentially signaling that something has gone wrong and the normal flow of your program cannot continue. This means that the control is transferred to the nearest enclosing try-except block, which is a block of code designed to handle exceptions in a specific way. If there is no such block, the program will terminate, and the error message will be displayed.
But why is it so important to raise exceptions in the first place? Well, doing so can actually help you create more robust and error-resilient code. By detecting and handling errors early on in the code, you can prevent them from causing unexpected behavior or even crashing your program altogether. This can save you time and frustration in the long run, as well as make your code more reliable and easier to maintain.
Exercise 9.3.1: Raising Exceptions for Invalid Input
Title: Validate User Input
Description: Write a function called validate_input
that takes a string as its input and raises a ValueError
exception if the input string contains any special characters (e.g., !
, @
, #
, etc.).
Instructions:
- Create a function
validate_input
that takes a stringinput_str
. - Check if the input string contains any special characters.
- If it does, raise a
ValueError
with a custom error message. - Test the function with valid and invalid inputs using a try-except block.
Solution:
import string
def validate_input(input_str):
if any(char in string.punctuation for char in input_str):
raise ValueError("Invalid input: The input should not contain special characters")
try:
validate_input("HelloWorld!")
except ValueError as ve:
print(ve)
try:
validate_input("HelloWorld")
except ValueError as ve:
print(ve)
Output:
Invalid input: The input should not contain special characters
Exercise 9.3.2: Raising Exceptions for Invalid Passwords
Title: Password Strength Checker
Description: Create a function called validate_password
that checks if a given password is strong. A strong password is defined as having at least 8 characters, containing at least one uppercase letter, one lowercase letter, one digit, and one special character. Raise a ValueError
exception if the password does not meet these criteria.
Instructions:
- Create a function
validate_password
that takes a stringpassword
. - Check if the password meets the criteria for a strong password.
- If it does not, raise a
ValueError
with a custom error message. - Test the function with valid and invalid passwords using a try-except block.
Solution:
import string
def validate_password(password):
if len(password) < 8:
raise ValueError("Invalid password: Password must have at least 8 characters")
if not any(char.isupper() for char in password):
raise ValueError("Invalid password: Password must have at least one uppercase letter")
if not any(char.islower() for char in password):
raise ValueError("Invalid password: Password must have at least one lowercase letter")
if not any(char.isdigit() for char in password):
raise ValueError("Invalid password: Password must have at least one digit")
if not any(char in string.punctuation for char in password):
raise ValueError("Invalid password: Password must have at least one special character")
try:
validate_password("WeakPwd1")
except ValueError as ve:
print(ve)
try:
validate_password("StrongPwd1!")
except ValueError as ve:
print(ve)
Output:
Invalid password: Password must have at least one special character
Exercise 9.3.3: Raising Exceptions for Invalid Email Addresses
Title: Email Validator
Description: Create a function called validate_email
that checks if a given email address is valid. A valid email address should have the following format: <username>@<domain>.<tld>
. Raise a ValueError
exception if the email address does not meet these criteria.
Instructions:
- Create a function
validate_email
that takes a stringemail
. - Check if the email address is valid.
- If it is not, raise a
ValueError
with a custom error message. - Test the function with valid and invalid email addresses using a try-except block.
Solution:
import re
def validate_email(email):
email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not re.match(email_regex, email):
raise ValueError("Invalid email address")
try:
validate_email("invalid_email.com")
except ValueError as ve:
print(ve)
try:
validate_email("valid.email@example.com")
except ValueError as ve:
print(ve)
Output:
Invalid email address
9.3: Raising Exceptions
In Python, exceptions are events that can occur when there is an error or an exceptional condition during the execution of a program. These can be caused by a variety of factors, such as incorrect input or an unexpected event. As we have seen before, Python automatically raises exceptions when it encounters an error.
However, you can also manually raise exceptions in your code by using the raise
statement. This is particularly useful when you want to enforce certain conditions or constraints in your program, such as checking for valid input or ensuring that certain resources are available before executing a piece of code.
To raise an exception, you can use the raise
keyword followed by the exception class or an instance of the exception class you want to raise. This can be helpful in providing additional context for the error, such as specifying the type of error that occurred or providing a custom message to the user. By raising exceptions in your code, you can improve its robustness and make it more reliable, ensuring that it can handle a wide range of inputs and conditions.
Here is the basic syntax for raising an exception:
raise ExceptionClass("Error message")
For example, you can raise a ValueError
exception if you want to enforce that a certain value should be within a specific range:
def validate_age(age):
if age < 0 or age > 150:
raise ValueError("Invalid age: Age must be between 0 and 150")
try:
validate_age(-5)
except ValueError as ve:
print(ve)
In this example, the validate_age
function checks if the given age is within the valid range (0 to 150). If it is not, a ValueError
exception is raised with a custom error message. We then use a try-except block to call the function and handle the exception if it occurs.
When you raise an exception in your code, you are essentially signaling that something has gone wrong and the normal flow of your program cannot continue. This means that the control is transferred to the nearest enclosing try-except block, which is a block of code designed to handle exceptions in a specific way. If there is no such block, the program will terminate, and the error message will be displayed.
But why is it so important to raise exceptions in the first place? Well, doing so can actually help you create more robust and error-resilient code. By detecting and handling errors early on in the code, you can prevent them from causing unexpected behavior or even crashing your program altogether. This can save you time and frustration in the long run, as well as make your code more reliable and easier to maintain.
Exercise 9.3.1: Raising Exceptions for Invalid Input
Title: Validate User Input
Description: Write a function called validate_input
that takes a string as its input and raises a ValueError
exception if the input string contains any special characters (e.g., !
, @
, #
, etc.).
Instructions:
- Create a function
validate_input
that takes a stringinput_str
. - Check if the input string contains any special characters.
- If it does, raise a
ValueError
with a custom error message. - Test the function with valid and invalid inputs using a try-except block.
Solution:
import string
def validate_input(input_str):
if any(char in string.punctuation for char in input_str):
raise ValueError("Invalid input: The input should not contain special characters")
try:
validate_input("HelloWorld!")
except ValueError as ve:
print(ve)
try:
validate_input("HelloWorld")
except ValueError as ve:
print(ve)
Output:
Invalid input: The input should not contain special characters
Exercise 9.3.2: Raising Exceptions for Invalid Passwords
Title: Password Strength Checker
Description: Create a function called validate_password
that checks if a given password is strong. A strong password is defined as having at least 8 characters, containing at least one uppercase letter, one lowercase letter, one digit, and one special character. Raise a ValueError
exception if the password does not meet these criteria.
Instructions:
- Create a function
validate_password
that takes a stringpassword
. - Check if the password meets the criteria for a strong password.
- If it does not, raise a
ValueError
with a custom error message. - Test the function with valid and invalid passwords using a try-except block.
Solution:
import string
def validate_password(password):
if len(password) < 8:
raise ValueError("Invalid password: Password must have at least 8 characters")
if not any(char.isupper() for char in password):
raise ValueError("Invalid password: Password must have at least one uppercase letter")
if not any(char.islower() for char in password):
raise ValueError("Invalid password: Password must have at least one lowercase letter")
if not any(char.isdigit() for char in password):
raise ValueError("Invalid password: Password must have at least one digit")
if not any(char in string.punctuation for char in password):
raise ValueError("Invalid password: Password must have at least one special character")
try:
validate_password("WeakPwd1")
except ValueError as ve:
print(ve)
try:
validate_password("StrongPwd1!")
except ValueError as ve:
print(ve)
Output:
Invalid password: Password must have at least one special character
Exercise 9.3.3: Raising Exceptions for Invalid Email Addresses
Title: Email Validator
Description: Create a function called validate_email
that checks if a given email address is valid. A valid email address should have the following format: <username>@<domain>.<tld>
. Raise a ValueError
exception if the email address does not meet these criteria.
Instructions:
- Create a function
validate_email
that takes a stringemail
. - Check if the email address is valid.
- If it is not, raise a
ValueError
with a custom error message. - Test the function with valid and invalid email addresses using a try-except block.
Solution:
import re
def validate_email(email):
email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not re.match(email_regex, email):
raise ValueError("Invalid email address")
try:
validate_email("invalid_email.com")
except ValueError as ve:
print(ve)
try:
validate_email("valid.email@example.com")
except ValueError as ve:
print(ve)
Output:
Invalid email address