atxdba
atxdba

Reputation: 5216

try catch coding pattern in python

I'm dealing with a set of 3rd party python scripts. I'm noticing this general pattern of enumerating many different Exception classes with no different action taken but logging a string representation of the exception that would be caught.

except AttributeError as ae:
        print("Attribute Error while processing the configuration file!\n{0}\n".format( str(ae) ) )
        intReturnValue = 1
    except IndexError as ie:
        print("Index Error while processing the configuration file!\n{0}\n".format( str(ie) ) )
        intReturnValue = 1
    except NameError as ne:
        print("Name Error while processing the configuration file!\n{0}\n".format( str(ne) ) )
        intReturnValue = 1
    except TypeError as te:
        print("Type Error while processing the configuration file!\n{0}\n".format( str(te) ) )
        intReturnValue = 1
    except:
        print("Unexpected error while processing the configuration file!\n{0}\n".format( sys.exc_info()[0] ) )
        intReturnValue = 1

Is this pattern some kind of pythonism or more just the author? It seems python allows you to have a general case catch block. Wouldn't it be simpler in this case to just use that and generate the log message a bit more dynamically?

Upvotes: 2

Views: 240

Answers (3)

Ben
Ben

Reputation: 2472

The normal way to write this would be

except (AttributeError, IndexError, NameError, TypeError) as ex:
    print("{} while processing the configuration file!\n{}\n".format(type(ex).__name, ex)
except BaseException:
        print("Unexpected error while processing the configuration file!\n{0}\n".format( sys.exc_info()[0] ) )

Or better yet:

except BaseException as ex:
    print("{} while processing the configuration file!\n{}\n".format(type(ex).__name, ex)

EDIT

Catching BaseException is generally bad, but no worse than a bare except.

Upvotes: 3

Joran Beasley
Joran Beasley

Reputation: 113950

I think it would be better to do something like

ERROR_CONDITIONS = AttributeError,IndexError,NameError,TypeError
try:
   ...
except ERROR_CONDITIONS as ae:
    print("Attribute Error while processing the configuration file!\n{0}\n".format( str(ae) ) )
    intReturnValue = 1
except:
     #unknown errror

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599540

Wow, that is pretty poor code. You certainly can catch a series of exceptions at once and log them:

except (AttributeError, IndexError, NameError, TypeError) as e:
    print "%s was raised... " % (e.__class__.__name__)

Of course, you should then probably determine why that code needs to catch all those different exception types. It sounds like something seriously wrong with the processing code itself.

Upvotes: 6

Related Questions