Welcome back to CodeYourCraft! Today, we're diving into one of Python's powerful features - Multiple Exceptions. This lesson is perfect for both beginners and intermediates. Let's get started!
In simple terms, an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Python uses exceptions to signal that something went wrong.
Before we delve into multiple exceptions, let's quickly review single exceptions. In Python, we can use the try and except blocks to handle errors.
try:
# code that might raise an exception
print(5 / 0)
except ZeroDivisionError as e:
print("Caught an exception: ", e)In this example, we're trying to divide by zero, which results in a ZeroDivisionError. The except block catches this error and prints a helpful message.
Multiple exceptions allow us to handle multiple types of exceptions in a single try block. This is incredibly useful in real-world applications where various types of errors can occur.
try:
# code that might raise an exception
print(5 / 0)
file = open("nonexistent_file.txt", "r") # This will raise a FileNotFoundError
except (ZeroDivisionError, FileNotFoundError) as e:
print("Caught an exception: ", e)In this example, we're not only handling a ZeroDivisionError but also a FileNotFoundError. The parentheses around the exception types indicate that we're dealing with multiple exceptions.
You can also create your own custom exceptions to make your code more flexible and easy to understand.
class CustomError(Exception):
pass
def custom_function():
raise CustomError("An error occurred in custom_function.")
try:
custom_function()
except CustomError as e:
print("Caught a custom exception: ", e)In this example, we've created a CustomError class that inherits from Python's built-in Exception class. We then raise this custom exception in our function, and handle it using the except block.
Which of the following is used to handle exceptions in Python?
What does the `pass` keyword do in Python's custom exception?
That's it for today! We've covered multiple exceptions and even touched on creating custom exceptions. As always, practice makes perfect. Try to implement these concepts in your own projects and feel free to reach out if you have any questions. Happy coding! 💻💻💻