Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在自己的类中捕获python异常_Python_Exception - Fatal编程技术网

在自己的类中捕获python异常

在自己的类中捕获python异常,python,exception,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.en

我现在有个奇怪的问题。 在我的程序中,我试图捕获类内部的异常,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()
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
输出

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")' ()
回溯(最近一次呼叫最后一次):
正在尝试构建SQLEngine
文件“/home/tom/Projects/test/test/test.py”,第11行,在
课堂测试:
文件“/home/tom/Projects/test/test/test.py”,第23行,测试中
database=DB(数据库路径)
文件“/home/tom/Projects/test/test/helpers/db.py”,第19行,在__
self.buildDatabaseModels()
buildDatabaseModels中的文件“/home/tom/Projects/test/test/helpers/db.py”,第39行
Base.metadata.create_all(self.SQLEngine,checkfirst=True)
文件“/home/tom/Projects/test/local/lib/python2.7/site packages/sqlalchemy/sql/schema.py”,第3308行,在create_all中
表=表)
文件“/home/tom/Projects/test/local/lib/python2.7/site packages/sqlalchemy/engine/base.py”,第1516行,在“运行”中
连接运行访问者(访问者可调用,元素,**kwargs)
文件“/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py”,第1164行,在运行时访问
**kwargs)。单导线(元件)
文件“/home/tom/Projects/test/local/lib/python2.7/site packages/sqlalchemy/sql/visitors.py”,第119行,在traverse_single中
返回方法(obj,**kw)
文件“/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py”,第696行,访问元数据
如果是self.\u可以\u创建\u表(t)]
文件“/home/tom/Projects/test/local/lib/python2.7/site packages/sqlalchemy/sql/ddl.py”,第674行,在“cancreate”表中
table.name,schema=table.schema)
文件“/home/tom/Projects/test/local/lib/python2.7/site packages/sqlalchemy/dialogs/sqlite/base.py”,第781行,在has_表中
游标=_pragma_游标(connection.execute(语句))
文件“/home/tom/Projects/test/local/lib/python2.7/site packages/sqlalchemy/engine/base.py”,第709行,在execute中
返回self.\u执行\u文本(对象、多线程、参数)
文件“/home/tom/Projects/test/local/lib/python2.7/site packages/sqlalchemy/engine/base.py”,第858行,文本为
语句、参数
文件“/home/tom/Projects/test/local/lib/python2.7/site packages/sqlalchemy/engine/base.py”,第927行,在执行上下文中
(上下文)
文件“/home/tom/Projects/test/local/lib/python2.7/site packages/sqlalchemy/engine/base.py”,第1076行,在_handle_dbapi_exception中
exc_信息
文件“/home/tom/Projects/test/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py”,第185行,源于
重新释放(类型(异常),异常,tb=exc_tb)
文件“/home/tom/Projects/test/local/lib/python2.7/site packages/sqlalchemy/engine/base.py”,第920行,在执行上下文中
(上下文)
文件“/home/tom/Projects/test/local/lib/python2.7/site packages/sqlalchemy/engine/default.py”,第425行,在do_execute中
cursor.execute(语句、参数)
sqlalchemy.exc.DatabaseError:(DatabaseError)文件已加密或不是数据库u'PRAGMA table_info(“groups”)()
DB.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()
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
从sqlalchemy导入创建引擎
从sqlalchemy.orm导入sessionmaker
从sqlalchemy.exc导入数据库错误,SQLAlchemyError
从模型导入*
从助手导入库
从helpers.crypt导入crypt
DB类:
SQLEngine=None
SessionMaker=None
会话=无
BuildEngineErrorCount=0
定义初始化(自我,数据库路径):
self.buildEngine(db_路径)
self.buildDatabaseModels()
def构建引擎(自身,数据库路径):
尝试:
self.SQLEngine=创建引擎('sqlite:////“+db_路径)
打印“尝试构建SQLEngine”
除此之外呢,呃,
打印“错误%s”%er
对于er.args中的错误:
如果错误=='(DatabaseError)文件已加密或不是数据库':
self.BuildEngineErrorCount+=1
c=Crypt()
c、 设置键(“测试”)
c、 解密数据库(数据库路径)
如果self.BuildEngineErrorCount小于5:
self.buildEngine(db_路径)
def buildDatabaseModels(自):
如果self.SQLEngine为无:
引发异常(“未找到SQLEngine”)
Base.metadata.create_all(self.SQLEngine,checkfirst=True)
def createSession(自):
如果self.SessionMaker不是None或self.Session不是None:
引发异常(“会话已映射”)
self.SessionMaker=SessionMaker(bind=self.SQLEngine)
self.Session=self.SessionMaker()
返回self.Session
正如您所看到的,我试图在db类中捕获该异常,但它没有捕获任何内容。
有人知道我做错了什么吗?

您的异常来自不同的方法,而不是您尝试的方法。具体来说,例外情况来自

Base.metadata.create_all(self.SQLEngine, checkfirst=True)

buildDatabaseModels
中,但是除了在
buildEngine

Lol中,您已经尝试过了,您完全正确!我怎么会错过呢!:)Thnx,如果可以,我会将此标记为正确答案(需要等待6分钟)