简体   繁体   English

从一种方法到另一种方法的 Python 异常,它是如何工作的

[英]Python exception from one method to another, how does it work

Hi I'm a bit lost with the exception and error hierarchy and I'd like to know how to manage properly嗨,我对异常和错误层次结构有点迷茫,我想知道如何正确管理

Basically基本上

let's say I want to have a task with retry假设我想要重试任务

@app.MyTask(bind=True)
try:
 doThis()
except(MyException):
 self.retry()

Now I want to get this exception from an exception within a function called by DoThis.Let's make it simple with code:现在我想从 DoThis 调用的 function 中的异常中获取此异常。让我们用代码让它变得简单:

def DoThis():
 if a:
  doThat()
 else:
  doAnotherThing()

def doAnotherThing():
 try:
  havingfun()
 except (AnOtherException)
  raise MyException

So my question is, am I doing it the right way or should I do a try, except, and raise the same exception in DoThis like this所以我的问题是,我是否以正确的方式做这件事,或者我应该尝试一下,除了,并在 DoThis 中引发同样的异常,就像这样

def DoThis()
 if a:
  doThat()
else:
  try:
    doAnotherThing()
  except(MyException):
    raise(MyException)

There is no general rule on where and how to catch errors.关于在何处以及如何捕获错误没有一般规则。 What I personally would not do is, to catch an Exception just to rewrite it.我个人不会做的是,捕获一个异常只是为了重写它。

A small example:一个小例子:

from typing import Union

def outer_function(a: Union[list, None] ,b: Union[list, None]):
    try:
        inner_function(a, b)
    except TypeError:
        print("Log error somehow")

def inner_function(a: list, b: list) -> list:
        return a + b
        
outer_function([1,2,3], None)

The inner_function does expect two lists as inputs. inner_function 确实需要两个列表作为输入。 You do not assume an error to happen within that aux function.您不会假设该辅助 function 中发生错误。 And such a function does normally not hold the info of how to handle the exception.而这样的 function 通常不包含如何处理异常的信息。

The outer_function does asume (stupid example) that a and b may be None. outer_function 确实假设(愚蠢的例子)a 和 b 可能是 None。 Therefore a TypeError is to be expected in some cases.因此,在某些情况下会出现 TypeError。

Therefore we catch the exception (always as precise as possible) -> TypeError.因此我们捕获异常(总是尽可能精确)-> TypeError。

Now we log it and handle it with some logic.现在我们记录它并用一些逻辑处理它。

Not sure if that was your question after rereading it..不知道这是否是你重读后的问题..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM