Q1. How do you create a custom exception in Python?
Define a new class that inherits from Exception (or a subclass). Example:
class NegativeNumberError(Exception):
pass You can add custom attributes and __init__ for more information.Q2. Why would you use custom exceptions?
Custom exceptions make your code more readable and allow you to handle specific error conditions in a domain-specific way. They can carry additional context (like an error code) and can be caught separately from built-in exceptions.
Q3. How do you raise a custom exception?
Just like any exception, use raise. Example:
if value < 0:
raise NegativeNumberError("Value cannot be negative")Q4. Can custom exceptions have additional attributes?
Yes, you can define __init__ to set custom attributes. Example:
class ValidationError(Exception):
def __init__(self, field, message):
self.field = field
self.message = message
super().__init__(f"{field}: {message}")Q5. How do you catch a custom exception?
Same as built-in exceptions. Example:
try:
# code that might raise NegativeNumberError
except NegativeNumberError as e:
print(f"Error: {e}")