在自己的类中捕获python异常

时间:2014-03-16 11:25:29

标签: python exception

我现在有一个奇怪的问题。 在我的程序中,我尝试在类中捕获异常,de class在一个单独的python文件中使用,但异常气泡通过调用文件。 我该如何解决这个问题?

示例:

main.py

#from sqlalchemy.exc import SQLAlchemyError, DatabaseError
from os import path

from helpers.db import DB
from models.group import Group
from models.entity import Entity
PROJECT_PATH = path.split(path.abspath(__file__))[0]
DATABASE_PATH = PROJECT_PATH + '/datastore/test.db'

class PasswordManager:
    database = DB(DATABASE_PATH)

if __name__ == "__main__":
    PasswordManager()

输出

Traceback (most recent call last):
trying to build a SQLEngine
  File "/home/tom/Projects/test/test/test.py", line 11, in <module>
    class test:
  File "/home/tom/Projects/test/test/test.py", line 23, in test
    database = DB(DATABASE_PATH)
  File "/home/tom/Projects/test/test/helpers/db.py", line 19, in __init__
    self.buildDatabaseModels()
  File "/home/tom/Projects/test/test/helpers/db.py", line 39, in buildDatabaseModels
    Base.metadata.create_all(self.SQLEngine, checkfirst=True)
  File "/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 3308, in create_all
    tables=tables)
  File "/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1516, in _run_visitor
    conn._run_visitor(visitorcallable, element, **kwargs)
  File "/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1164, in _run_visitor
    **kwargs).traverse_single(element)
  File "/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py", line 119, in traverse_single
    return meth(obj, **kw)
  File "/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 696, in visit_metadata
    if self._can_create_table(t)]
  File "/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 674, in _can_create_table
    table.name, schema=table.schema)
  File "/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/dialects/sqlite/base.py", line 781, in has_table
    cursor = _pragma_cursor(connection.execute(statement))
  File "/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 709, in execute
    return self._execute_text(object, multiparams, params)
  File "/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 858, in _execute_text
    statement, parameters
  File "/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 927, in _execute_context
    context)
  File "/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1076, in _handle_dbapi_exception
    exc_info
  File "/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 185, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb)
  File "/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 920, in _execute_context
    context)
  File "/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 425, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.DatabaseError: (DatabaseError) file is encrypted or is not a database u'PRAGMA table_info("groups")' ()

DB.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import DatabaseError, SQLAlchemyError

from models import *
from helpers import Base
from helpers.crypt import Crypt

class DB:
    SQLEngine = None
    SessionMaker = None
    Session = None
    BuildEngineErrorCount = 0

    def __init__(self, db_path):
        self.buildEngine(db_path)
        self.buildDatabaseModels()

    def buildEngine(self, db_path):
        try:
            self.SQLEngine = create_engine('sqlite:////' + db_path)
            print "trying to build a SQLEngine"
        except BaseException, er:
            print "Errors %s" % er
            for error in er.args:
                if error == '(DatabaseError) file is encrypted or is not a database':
                    self.BuildEngineErrorCount += 1
                    c = Crypt()
                    c.setKey('Test')
                    c.decryptDB(db_path)
                    if self.BuildEngineErrorCount < 5:
                        self.buildEngine(db_path)

    def buildDatabaseModels(self):
        if self.SQLEngine is None:
            raise Exception("No SQLEngine found")
        Base.metadata.create_all(self.SQLEngine, checkfirst=True)

    def createSession(self):
        if self.SessionMaker is not None or self.Session is not None:
            raise Exception("Session already mapped")

        self.SessionMaker = sessionmaker(bind=self.SQLEngine)
        self.Session = self.SessionMaker()
        return self.Session

正如您所看到的,我尝试在db类中捕获该异常,但它并没有抓住任何东西。 有谁知道我做错了什么?

1 个答案:

答案 0 :(得分:2)

您的异常来自与您放置try-except的方法不同的方法。具体来说,异常来自

Base.metadata.create_all(self.SQLEngine, checkfirst=True)
<{1>}中的

,但您在buildDatabaseModels中尝试了 -