2

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?

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I was going to say that, but I had to look it up! Too fast, man.
3

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.