在 python 方法中处理异常的合适方法是什么?

What is the appropriete way to handling exceptions inside a python method?

假设我有一个函数,并且根据它的输入,它必须 "advise" 调用函数出错了:

def get_task(msg, chat):
    task_id = int(msg)
    query = db.SESSION.query(Task).filter_by(id=task_id, chat=chat)
    try:
        task = query.one()
    except sqlalchemy.orm.exc.NoResultFound:
        return "_404_ error"
    return task

注意在 except 块我想传递一些调用函数可以处理的东西并在必要时停止它的执行,否则,它将 return 正确的对象。

def something_with_the_task(msg, chat):
   task = get_task(msg, chat)
   if task == "_404_ error":
       return
   #do some stuff with task

您似乎已经知道异常是如何工作的。

如果出现错误,最好的办法是 raise 异常。

返回一些 magic 值被认为是一种不好的做法,因为它需要调用者明确检查它,并且 hundred of other reasons.

您可以简单地让 sqlalchemy.orm.exc.NoResultFound 异常逃逸(通过删除 try:get_task() 中的 except: 块),并让调用者使用try: ... except: ... 块,或者,如果你喜欢做一些 hiding,你可以定义一个自定义异常:

class YourException(Exception):
    pass

并像这样使用它:

def get_task(msg, chat):
    try:
        task = ...
    except sqlalchemy.orm.exc.NoResultFound:
        raise YourException('explanation')
    return task

def something_with_the_task(msg, chat):
    try:
        task = get_task(msg, chat)
        # do some stuff with task
    except YourException as e:
        # do something with e
        # e.args[0] will contain 'explanation'

如果需要,可以通过显式添加一些属性和用于设置这些属性的构造函数来使 YourException class 提供更多信息。

但是默认构造函数做得不错:

>>> e = YourException('Program made a boo boo', 42, 'FATAL')
>>> e
YourException('Program made a boo boo', 42, 'FATAL')
>>> e.args[0]
'Program made a boo boo'
>>> e.args[1]
42
>>> e.args[2]
'FATAL'