Custom Exceptions

Simple Custom Exception

  1. # define custom exception
  2. class CustomError(Exception):
  3. pass
  4. #ans: raise it
  5. raise CustomError("Something went wrong")

Exception with Attributes

  1. # exception with data
  2. class ValidationError(Exception):
  3. def __init__(self, field, message):
  4. self.field = field
  5. self.message = message
  6. super().__init__(f"{field}: {message}")

Using Custom Exception

  1. # raise custom exception
  2. try:
  3. raise ValidationError("email", "Invalid format")
  4. except ValidationError as e:
  5. print(e.field)
  6. print(e.message)

Exception Hierarchy

  1. # base exception
  2. class DatabaseError(Exception):
  3. pass
  4. #ans: specific exceptions
  5. class ConnectionError(DatabaseError):
  6. pass
  7. class QueryError(DatabaseError):
  8. pass

Exercises - Part 1

  1. # inherit from what?
  2. class MyError(Exception):
  3. pass
  4. #ans: inherits from Exception

Exercises - Part 2

  1. # can inherit from BaseException?
  2. class MyError(BaseException):
  3. pass
  4. #ans: yes, but use Exception instead

Exercises - Part 3

  1. # custom message?
  2. class MyError(Exception):
  3. pass
  4. raise MyError("Custom message")
  5. #ans: works!

Exercises - Part 4

  1. # catch custom exception?
  2. try:
  3. raise CustomError()
  4. except CustomError:
  5. print("Caught")
  6. #ans: "Caught"

Exercises - Part 5

  1. # exception with default message?
  2. class MyError(Exception):
  3. def __init__(self):
  4. super().__init__("Default message")

Exercises - Part 6

  1. # multiple custom exceptions?
  2. class Error1(Exception):
  3. pass
  4. class Error2(Exception):
  5. pass
  6. try:
  7. pass
  8. except (Error1, Error2):
  9. pass

Exercises - Part 7

  1. # exception hierarchy catch?
  2. class Base(Exception):
  3. pass
  4. class Derived(Base):
  5. pass
  6. try:
  7. raise Derived()
  8. except Base:
  9. print("Caught")
  10. #ans: "Caught"

Exercises - Part 8

  1. # custom exception attributes?
  2. class MyError(Exception):
  3. def __init__(self, code):
  4. self.code = code

Exercises - Part 9

  1. # exception with __str__?
  2. class MyError(Exception):
  3. def __str__(self):
  4. return "Custom string"

Exercises - Part 10

  1. # empty custom exception?
  2. class MyError(Exception):
  3. pass
  4. #ans: valid minimal exception

Google tag (gtag.js)