Week 10: Mastering Error Handling
Learn how to deal with errors and exceptions in Python to make your programs more robust.
Explore Chapter 10Raising Exceptions.
In addition to handling exceptions, you can also explicitly raise exceptions in your code using the `raise` statement. This is useful when you want to signal that an error condition has occurred.
`raise` Statement
raise ExceptionType("Error message")
You can raise built-in exceptions or create your own custom exception classes (we won't cover custom exception classes in this introductory course).
Example
def get_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
return age
try:
user_age = int(input("Enter your age: "))
age = get_age(user_age)
print("Age:", age)
except ValueError as e:
print("Error:", e)
In this example, the `get_age` function raises a `ValueError` if the provided age is negative. The `try-except` block handles this exception and prints an appropriate error message.