简体   繁体   中英

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

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. I know that my code works like this, but I was wondering if this is good practice and/or the pythonic way of working.

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.

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
  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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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