try-except with no exceptions

Peter Otten __peter__ at web.de
Thu Oct 13 12:46:15 EDT 2016


Daiyue Weng wrote:

> Hi, I have seen code using try_except with no exceptions,
> 
> from dateutil import parser
> 
> try:
>     from_date = datetime.datetime.strptime(parameters['from_date'],
> '%Y-%m-%d %H:%M:%S.%f')
>     to_date = datetime.datetime.strptime(parameters['to_date'],
> '%Y-%m-%d %H:%M:%S.%f')
> except:
>     from_date = parser.parse(parameters['from_date'])
>     to_date = parser.parse(parameters['to_date'])
> 
> 
> I know that such try-catch usage is generally a bad practice, since it
> can't locate the root of the exceptions.
> 
> I am wondering how to correct the code above (what it tries to do is
> basically trying one processing block, if not working, running another
> block of code in except). Also a warning 'Too broad exception clause'
> will be generated.

Is it intentional that both times have to be parsed by the same function?
If not I'd do

def parse_date(datestr):
    try:
        return datetime.datetime.strptime(datestr, '%Y-%m-%d %H:%M:%S.%f')
    except ValueError:
        return dateutil.parser.parse(datestr)


from_date = parse_date(parameters['from_date'])
to_date = parse_date(parameters['to_date'])

Exceptions other than ValueError are probably hints that the program logic 
is flawed, so I'd rather have them bubble up.




More information about the Python-list mailing list