pandas 我应该把 try/except 放在哪里?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31632050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where should I put try/except?
提问by GiannisIordanou
In an effort to improve my coding, I was wondering if I should put try/except inside a function or keep it outside. The following examples display what I mean.
为了改进我的编码,我想知道是否应该将 try/except 放在函数内部或将其保留在外部。以下示例显示了我的意思。
import pandas as pd
df = pd.read_csv("data.csv")
# Example 1
def do_something(df):
# Add some columns
# Split columns
return df
try:
df = do_something(df)
except Exception, e:
print e
# Example 2
def do_something(df):
try:
# Add some columns
# Split columns
except Exception, e:
print e
df = pd.DataFrame()
return df
df = do_something(df)
It might seem the same, but the first example is more clear on what happens while the second seems cleaner.
看起来可能是一样的,但第一个示例更清楚地说明了会发生什么,而第二个示例更清晰。
回答by bakkal
Possibility of internal handling
内部处理的可能性
If the function can provide a sensiblerecovery from the exception and handle it within its scope of responsibilities and without any additional information, then you can catch the exception right there
如果该函数可以从异常中提供合理的恢复并在其职责范围内处理它并且无需任何附加信息,那么您可以在那里捕获异常
Raise or translate to caller
提高或翻译给来电者
Otherwise, it might be better left up to the caller to deal with it. And sometimes even in this case, the function might catch the exception and then immediately raise it again with a translation that makes sense to the caller
否则,最好由调用者来处理它。有时即使在这种情况下,该函数也可能会捕获异常,然后立即使用对调用者有意义的翻译再次引发它
回答by Reut Sharabani
It has nothing to do with how it looks, it has to do with where can you handle the exception.
它与它的外观无关,而与您可以在哪里处理异常有关。
If the exception can be handled inside the function - use it there. If it can't - use it outside the function.
如果异常可以在函数内部处理 - 在那里使用它。如果不能 - 在函数之外使用它。
As an example:
举个例子:
def pi():
try:
return get_awsome_pi_value_from_internetz()
except NoInternetzError:
# recover
return 3.14
Or an example where the error can't be handled:
或无法处理错误的示例:
def get_square_root(x):
return x ** 0.5
Elsewhere in code:
代码中的其他地方:
try:
get_square_root(-1) # imagine -1 was received from user
except ValueError:
print("Can't find a sensible root for value.")
# recover / panic
回答by Incognos
Generally speaking, You would use try/exceptif you anticipate a potential exception of a specific type. If you catch the exception, your application can continue running while you handle the exception in code. For example:
一般来说,try/except如果您预计特定类型的潜在异常,您将使用。如果您捕获异常,您的应用程序可以在您在代码中处理异常时继续运行。例如:
try:
user = User.objects.get(pk=id)
except ObjectDoesNotExist:
print("could not find user")
If you did not wrap that in a try except block, it would throw an exception because the user does not exist. This also saves you from having to call the db to check if the user exists before trying to get him.
如果你没有将它包装在 try except 块中,它会抛出异常,因为用户不存在。这也使您不必在尝试获取用户之前调用数据库来检查用户是否存在。
There are a lot of built-in exceptionsto python itself. You can define your own by subclassing the Exception class.
python 本身有很多内置异常。您可以通过继承 Exception 类来定义您自己的。
Pandas also has a good set of pre-defined exceptionsto catch.
Pandas 也有一组很好的预定义异常可以捕获。
Django also has a set of exceptions(I am using one in my example)
Django 也有一组异常(我在我的例子中使用了一个)
It does not matter what you wrap, as long as you deal with the individual exceptions. You can catch them generally, but then you are not wholly sure as to which exception is being thrown.
只要您处理个别异常,您包装什么都没有关系。您通常可以捕获它们,但是您不能完全确定正在抛出哪个异常。

![pandas 如何处理 KeyError:“['blah'] 不在索引中”](/res/img/loading.gif)