了解Python异常处理中的raise

了解Python异常处理中的raise,python,exception,exception-handling,Python,Exception,Exception Handling,raise在处理python异常时做什么 我有一些密码 def func(): try : 'some code here' except Exception, e: some_issue_entry(False, ke) db_entry(False, ke) raise except KeyboardInterrupt, ke: some_issue_entry(False, ke) db_entry(False, ke

raise在处理python异常时做什么

我有一些密码

def func():
  try :
    'some code here'
  except Exception, e:
     some_issue_entry(False, ke)
     db_entry(False, ke)
     raise

  except KeyboardInterrupt, ke:
     some_issue_entry(False, ke)
     db_entry(False, ke)
     raise

  some_issue_entry(True, None)
  db_entry(True, None)
所以这里我要替换这段代码,因为我不想编写相同的代码,它是具有不同参数的公共函数:

def func():
  success, exec = True, None
  try :
    'some code here'
  except Exception, e:
     success, exec = False, e

  except KeyboardInterrupt, ke:
     success, exec = False, ke

  some_issue_entry(success, exec)
  db_entry(success, exec)

  if not success:
     raise
以下是我的问题:

  • just
    raise
    如何处理异常和区分。因为使用第一种样式会引发正确的异常。它是否从本地存储的异常中选择

  • 虽然使用第二种风格也很有效(未经充分测试),但我不知道为什么我认为加薪和尝试有关,除了。使用第二种样式安全吗


  • Python将最后捕获的异常与当前线程上下文一起存储。因此,
    raise
    所要做的就是:

    其中
    PyThreadState\u GET()
    查找当前线程上下文

    这通过以下文件记录:

    如果不存在表达式,raise将重新引发当前作用域中活动的最后一个异常

    这里的范围是整个功能,而不仅仅是
    ,除了
    套件

    do_raise(PyObject *type, PyObject *value, PyObject *tb)
    {
        if (type == NULL) {
            /* Reraise */
            PyThreadState *tstate = PyThreadState_GET();
            type = tstate->exc_type == NULL ? Py_None : tstate->exc_type;
            value = tstate->exc_value;
            tb = tstate->exc_traceback;
            Py_XINCREF(type);
            Py_XINCREF(value);
            Py_XINCREF(tb);
        }