How do you create custom exceptions in Python?
a) By creating a new class that inherits from the Exception class
b) By using the try-except block
c) By overriding the raise statement
d) By creating a new function that handles errors
Answer:
a) By creating a new class that inherits from the Exception class
Explanation:
Custom exceptions in Python are created by defining a new class that inherits from the built-in Exception
class (or any of its subclasses). Custom exceptions allow you to define specific error types that are meaningful to your application, making it easier to handle and debug specific error conditions.
class NegativeValueError(Exception):
"""Exception raised for errors in the input if the value is negative."""
def __init__(self, value):
self.value = value
self.message = f"Negative value error: {value} is not allowed."
super().__init__(self.message)
def check_positive(number):
if number < 0:
raise NegativeValueError(number)
return number
try:
result = check_positive(-5)
except NegativeValueError as e:
print(e) # Output: Negative value error: -5 is not allowed.
In this example, a custom exception NegativeValueError
is defined by inheriting from the Exception
class. This custom exception is raised when a negative number is passed to the check_positive
function.
Creating custom exceptions allows you to provide more informative error messages and handle specific error conditions in a way that is tailored to your application’s needs.