简体   繁体   English

在python中编写库时如何处理异常

[英]how to handle exceptions while writing a library in python

Consider writing a small library in python that has this one simple method x which accepts an argument ac & returns the computed value 10/ac .考虑用 python 编写一个小库,它有一个简单的方法x ,它接受一个参数ac并返回计算值10/ac now the catch here is ac cannot be 0 .现在这里的问题是ac不能是0 so how do i handle this case in my method.there are these ways that comes to my mind.那么我如何在我的方法中处理这种情况。我想到了这些方法。

NOTE: i have looked into python exception handling but it just shows how to use try except not the specific problem that i am asking.注意:我已经研究了 python 异常处理,但它只是展示了如何使用try except我要问的特定问题try except

method 1方法一

def x(ac):
    try:
        return (10/ac)
    except  ZeroDivisionError:
        raise ZeroDivisionError("ac cannot be zero")

The above code just uses a plain try except block to catch spcific exceptions and raises the exception to the calling code.上面的代码只是使用一个普通的 try except 块来捕获特定的异常并将异常引发给调用代码。 so the calling code would look like this:所以调用代码看起来像这样:

# some script...
try:
    x(0)
except ZeroDivisionError as e:
    log(e)

but in this case, i would have to know before hand what all possible exceptions that method x might raise.但在这种情况下,我必须事先知道方法x可能引发的所有可能的异常。

Method 2:方法二:

def x(ac):
    if ac == 0:
        raise ValueError("ac cannot be zero") # or ZeroDivisionError??
    else:
        return (10/ac)

i guess this is semantically same as previous one except that to check some conditions(that we know might occur) using if's & raising exceptions based on that.我想这在语义上与前一个相同,除了使用if's和基于此引发异常来检查某些条件(我们知道可能会发生)。 It also suffers from the same problem of knowing beforehand what exceptions the method might throw.它还面临着同样的问题,即事先知道该方法可能抛出哪些异常。

method 3方法三

The last method is not handling any exception in the library method rather leave it to the client code but this obviously doesn't makes sense as the client would never be able to know why exactly the error might occur while resort to something like最后一种方法不是处理库方法中的任何异常,而是将其留给客户端代码,但这显然没有意义,因为客户端永远无法知道为什么在求助于类似的东西时可能会发生错误

def x(ac):
    return (10/ac)


    try:
       x(20)
    except Exception as e:
       log(e)

now this method here was a simple method with just one opertaion but what if the method itself is doing something complicated like connecting to the database then fetching some results.现在这里的这个方法是一个简单的方法,只有一个操作,但是如果方法本身正在做一些复杂的事情,比如连接到数据库然后获取一些结果怎么办。 something like :就像是 :

def x(db):
    conn = db.connect('localhost')
    results = connec.fetch(user_id=2)
    return results

if something is unclear please let me know.如果有什么不清楚,请告诉我。

It depends .这取决于 Exceptions like TypeError or ValueError are standard and usually indicate programming errors. TypeErrorValueErrorTypeError是标准的,通常表示编程错误。 There is usually no need to be explicit about these.通常不需要明确说明这些。

The rest, you document .其余的,您记录. As an API author it's your responsibility to make it clear what behaviour another developer can expect from your code.作为 API 作者,您有责任明确其他开发人员可以从您的代码中获得哪些行为。 If ZeroDivisionError is a good signal to document, then add that to the docstring of the API.如果ZeroDivisionError是一个很好的记录信号,则将其添加到 API 的文档字符串中。 At that point there is no need to explicitly catch and raise it again either.在这一点上,也不需要明确地捕获并再次提出它。 Don't count on the users reading your code, give them good documentation instead.不要指望用户阅读你的代码,而是给他们好的文档。

For many APIs it makes sense to define your own exceptions.对于许多 API 来说,定义自己的异常是有意义的。 The implementation can catch generic exceptions, or the custom exceptions of 3rd-party APIs it uses to do the work, then raise an API-specific exception to signal to the caller something is wrong, letting them handle the issue.该实现可以捕获通用异常,或者它用来完成工作的第 3 方 API 的自定义异常,然后引发特定于 API 的异常以向调用者发出错误信号,让他们处理问题。

There are legion examples of popular Python libraries with such exceptions.有很多流行的 Python 库的例子有这样的例外。 Some examples:一些例子:

What these projects have in common is good documentation , that explicitly names the exceptions that anyone using the project should be aware of.这些项目的共同点是良好的文档,明确命名了使用该项目的任何人都应该注意的例外情况。

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

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