Welcome to our comprehensive guide on understanding and using Custom Exceptions in Python! This tutorial is designed for beginners and intermediate learners, providing a thorough yet easy-to-follow explanation of this powerful feature. Let's dive right in!
Exceptions are errors or events that occur during the execution of a program. They can help us manage unexpected situations and make our code more robust.
By default, Python provides a variety of built-in exceptions like ZeroDivisionError, NameError, and TypeError. But sometimes, we might encounter situations where none of the built-in exceptions suit our needs. That's where Custom Exceptions come into play.
Python allows us to create our own exceptions by defining a new class that inherits from the built-in Exception class. Let's create a custom exception for invalid user inputs:
class InvalidInputError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.messageNow, we can raise our custom exception when required:
try:
user_input = int(input("Enter an integer: "))
if user_input < 0:
raise InvalidInputError("Negative numbers are not allowed.")
except InvalidInputError as e:
print(e)In this example, we've created a custom exception InvalidInputError and used it to handle the case where the user enters a negative number.
You can raise multiple exceptions in Python by using multiple raise statements or by chaining them with commas. Here's an example:
class MyCustomException(Exception):
def __init__(self, msg1, msg2):
self.msg1 = msg1
self.msg2 = msg2
def __str__(self):
return f"{self.msg1}\n{self.msg2}"
try:
x = 1/0 # Raises a ZeroDivisionError
raise MyCustomException("Custom Error 1", "Custom Error 2")
except ZeroDivisionError:
print("Handling ZeroDivisionError")
except MyCustomException as e:
print(e)In this example, we've raised both a ZeroDivisionError and a custom exception MyCustomException. The code handles the ZeroDivisionError separately and catches the custom exception using a specific exception block.
What is the purpose of Custom Exceptions in Python?
By the end of this tutorial, you should have a good understanding of creating and handling custom exceptions in Python. Happy coding! 🎉