# define custom exceptionclass CustomError(Exception): pass#ans: raise itraise CustomError("Something went wrong")
# exception with dataclass ValidationError(Exception): def __init__(self, field, message): self.field = field self.message = message super().__init__(f"{field}: {message}")
# raise custom exceptiontry: raise ValidationError("email", "Invalid format")except ValidationError as e: print(e.field) print(e.message)
# base exceptionclass DatabaseError(Exception): pass#ans: specific exceptionsclass ConnectionError(DatabaseError): passclass QueryError(DatabaseError): pass
# inherit from what?class MyError(Exception): pass#ans: inherits from Exception
# can inherit from BaseException?class MyError(BaseException): pass#ans: yes, but use Exception instead
# custom message?class MyError(Exception): passraise MyError("Custom message")#ans: works!
# catch custom exception?try: raise CustomError()except CustomError: print("Caught")#ans: "Caught"
# exception with default message?class MyError(Exception): def __init__(self): super().__init__("Default message")
# multiple custom exceptions?class Error1(Exception): passclass Error2(Exception): passtry: passexcept (Error1, Error2): pass
# exception hierarchy catch?class Base(Exception): passclass Derived(Base): passtry: raise Derived()except Base: print("Caught")#ans: "Caught"
# custom exception attributes?class MyError(Exception): def __init__(self, code): self.code = code
# exception with __str__?class MyError(Exception): def __str__(self): return "Custom string"
# empty custom exception?class MyError(Exception): pass#ans: valid minimal exception
Google tag (gtag.js)