Python Tutorial: Multiple Exceptions 🎯

beginner
5 min

Python Tutorial: Multiple Exceptions 🎯

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!

What are Exceptions in Python? 📝

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.

Single Exceptions 💡

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.

python
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.

Introducing Multiple Exceptions 💡

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.

python
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.

Pro Tip: Custom Exceptions 💡

You can also create your own custom exceptions to make your code more flexible and easy to understand.

python
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.

Quiz 🎯

Quick Quiz
Question 1 of 1

Which of the following is used to handle exceptions in Python?

Quick Quiz
Question 1 of 1

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! 💻💻💻