try-except with no exceptions

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Thu Oct 13 10:44:32 EDT 2016


Daiyue Weng writes:

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

Since help(datetime.strptime) didn't tell, I experimented with
datetime.strptime a bit. It seems to raise a ValueError when a string is
not formatted according to the pattern or has some component out of
range, and TypeError when given a non-string to parse. Tracebacks
indicate the exception type.

There's no point in catching KeyError, because the except clause would
do the same thing again.

try:
   # try with datetime.datetime.strptime
   ...
except (ValueError, TypeError):
   # try with dateutil.parser.parse
   ...

Also: https://docs.python.org/3/tutorial/errors.html



More information about the Python-list mailing list