0

Here's the code:

class SQLType(Enum):
    INTEGER = int
    TEXT = str


class SchemaError(Exception):
    print("I'd raise an exception...")
    # raise Exception("Incorrect Schema")
    
    
class DataBase:
    def __init__(self, location):
        self.location = location

    def __enter__(self):
        self.connection = sqlite3.connect(self.location)
        self.cursor = self.connection.cursor()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.connection.close()

    def create(self, table: str, schema: List[Tuple[str, SQLType]]):
        print("Init...")
        keys = [{s[0]: s[1].name} for s in schema]
        [...]

When calling it with:

CARS = [
    ("toyota", 100),
    ("fiat", 80),
    ("peugeot", 85),
    ("bmw", 160),
]

CAR_SCHEMA = [("car", SQLType.TEXT), ("avg_hp", SQLType.INTEGER)]

with DataBase("cars.db") as db:
    db.create("rankings", CAR_SCHEMA)

the first two lines of output are:

I'd raise an exception...
Init...

When the raise Exception statement is uncommented, it throws:

Traceback (most recent call last):
  File "[...]/sql_conn.py", line 17, in <module>
    class SchemaError(Exception):
  File "[...]/sql_conn.py", line 20, in SchemaError
    raise Exception("Incorrect Schema")
Exception: Incorrect Schema

Process finished with exit code 1

What's interesting for me, the exception gets raised even before the first instruction in the method is processed! So I guess there must be some check performed in this very place.

How should the arguments be processed within the create method so that it doesn't lead to raising an exception?

AbreQueVoy
  • 1,748
  • 8
  • 31
  • 52
  • Can you print the stack trace so you can see just what the problem is? – Scott Hunter Jun 17 '21 at 18:39
  • 1
    That message is printed because it's in the _class definition!_ The code in the class definition is executed when the script is run. If you want to print the message when an instance of the class is created, you should include it in the constructor for the class instead. – Pranav Hosangadi Jun 17 '21 at 18:43
  • @ScottHunter: added the stack trace to the post. It gets thrown right after the code gets executed. – AbreQueVoy Jun 18 '21 at 09:14

0 Answers0