简体   繁体   English

当您事先知道某些输入会出现问题时,使用 try/except 块来检查 function 是否可以安全运行是一种好习惯吗?

[英]Is it good practice to use try/except blocks to check if a function can safely be run when you know in advance some input will be problematic?

I was writing the following piece of code that converts a string to a float, where the string can have some additional non-digit characters (eg '~') where I have to deal with this in a certain way.我正在编写以下将字符串转换为浮点数的代码,其中字符串可以包含一些额外的非数字字符(例如'~'),我必须以某种方式处理这个问题。

My function looks something like this我的 function 看起来像这样

def convert(str): 
     try: 
         return float(str)
     except: 
         pass  
     if '~' in str: 
         # do something 
     # check other conditions

I'm essentially using the try/except block to check if the function float() is safe to use.我实际上是在使用 try/except 块来检查 function float()是否可以安全使用。 I know that my code works like this, but I was wondering if this is good practice and/or the pythonic way of working.我知道我的代码是这样工作的,但我想知道这是否是好的做法和/或 Python 的工作方式。

I feel like this isn't the way exceptions are meant to be used, because I know in advance that the string input has potential issues.我觉得这不是使用异常的方式,因为我事先知道字符串输入存在潜在问题。 I wonder if it is better practice to check for these issues in advance, and only use try/except to catch unexpected exceptions.我想知道提前检查这些问题是否更好,并且只使用 try/except 来捕获意外异常。

eg例如

def convert(str): 
     if '`' in str: 
         # do something 
     elif 'other condition' 
         # do someting else 
     else: 
         # at this point the string contains no other characters so I can safely use float 
         return float(str) 

Is one better than the other?这个比那个好吗? Or is this just a case of personal preference?或者这只是个人喜好?

Again, I know my original piece of code works so really I'm just wondering which of these two is best practice, and why (maybe either approach will cause errors in some cases) so that I can write the best possible code in the future.再次,我知道我的原始代码有效,所以真的我只是想知道这两个中哪一个是最佳实践,以及为什么(在某些情况下可能任何一种方法都会导致错误),以便我可以在未来编写最好的代码.

What you've done is almost OK with two exceptions:您所做的几乎可以,但有两个例外:

  1. I would make the further checks in the except body我会在 except 正文中进行进一步检查
  2. I would check for a specific Exception, because you are hiding potential problems you haven't thought about the way you are catching all possible exceptions.我会检查一个特定的异常,因为你隐藏了你没有考虑过捕获所有可能异常的方式的潜在问题。

So, it should look similar to this:所以,它应该看起来像这样:

def convert(str):
    try:
        return float(str)
    except ValueError:
        if '~' in str:
            # do something
            # check other conditions

        

I would recommend @Wankata solution and still add an extra except block to also handle all unexpected errors:我会推荐@Wankata 解决方案,并且仍然添加一个额外的 except 块来处理所有意外错误:

def convert(str):
    try:
        return float(str)
    except ValueError:
        if '~' in str:
            # do something
            # check other conditions
    except:
        # handle unexpected errors
        # display a warning, or log the error,
        # or return error code/default value, ...as you see fit

You can also look at the doc for the 'else' and 'finally' keywords which can be very usefull to handle some cases: https://docs.python.org/fr/3/tutorial/errors.html?highlight=try%20except您还可以查看文档中的“else”和“finally”关键字,这对于处理某些情况非常有用: https://docs.python.org/fr/3/tutorial/errors.ZFC35FZ?30D5try=C69D2368A %20 除外

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

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