引发异常与返回在函数中无? [英] Raise exception vs. return None in functions?

查看:97
本文介绍了引发异常与返回在函数中无?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中的用户定义函数中,更好的做法是:引发异常或不返回?例如,我有一个函数可以找到文件夹中的最新文件。

What's better practice in a user-defined function in Python: raise an exception or return None? For example, I have a function that finds the most recent file in a folder.

def latestpdf(folder):
    # list the files and sort them
    try:
        latest = files[-1]
    except IndexError:
        # Folder is empty.
        return None  # One possibility
        raise FileNotFoundError()  # Alternative
    else:
        return somefunc(latest)  # In my case, somefunc parses the filename

另一个选择是保留异常并在调用方代码中处理它,但我认为处理<$ c $更清楚c> FileNotFoundError IndexError 。还是用其他名称重新引发异常是不好的形式吗?

Another option is leave the exception and handle it in the caller code, but I figure it's more clear to deal with a FileNotFoundError than an IndexError. Or is it bad form to re-raise an exception with a different name?

推荐答案

这实际上是语义问题。 foo = Latestpdf(d) 平均值是什么?

It's really a matter of semantics. What does foo = latestpdf(d) mean?

没有最新文件?然后确定,只返回None。

Is it perfectly reasonable that there's no latest file? Then sure, just return None.

您是否希望总是找到最新文件?引发异常。是的,重新引发一个更合适的异常是可以的。

Are you expecting to always find a latest file? Raise an exception. And yes, re-raising a more appropriate exception is fine.

如果这只是应该应用于任何目录的通用函数,我会做一个不返回。如果该目录是(例如)要成为包含应用程序已知文件集的特定数据目录,则将引发异常。

If this is just a general function that's supposed to apply to any directory, I'd do the former and return None. If the directory is, e.g., meant to be a specific data directory that contains an application's known set of files, I'd raise an exception.

这篇关于引发异常与返回在函数中无?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆