Tuesday, May 3, 2011

Python - Possible to force raise exceptions regardless try/except blocks?

In Python is there any language (or interpreter) feature to force the python interpreter to always raise exceptions even if the exception offending code is inside a try/except block ?

I've just inherited a larger and old codebase written in python, whose purpose is to communicate with some custom designed hardware we also developed. Many communication errors and timeouts are being masked/missed due to the following (simplified) pattern of code:

try:
    serialport.write(MSG)
except:
    some_logging_function_mostly_not_working_that_might_be_here_or_not()
    #or just:
    #pass

In order to avoid the typical scenario of "just rewrite the whole thing from scratch", I'm currently trying to fix all exceptions errors/timeouts. I'm doing this by disabling by hand the all exception handling code, one at a time.

From stackoverflow
  • You can use multiple exception handlers to handle multiple exceptions.

    try:
        serialport.write(MSG)
    except Handler1:
        some_logging_function_mostly_not_working_that_might_be_here_or_not()
        #or just:
        #pass
    except Handler2:
        some_logging_function_mostly_not_working_that_might_be_here_or_not2()
        #or just:
        #pass
    
  • The "all-exceptions" except: block is a remarkably bad thing and must simply be found and replaced with sensible except handling.

    In this case grep is your friend. A good IDE can help make these unpleasant chores manageable.

    But there's no "ignore the code as written" option in Python.

    Jarret Hardie : +1 "ignore the code as written" :-)
    dangph : pyparsing is a useful tool for doing code transformation.
  • No, not really. Your best bet is to change the code to something more like this:

    try:
        serialport.write(MSG)
    except:
        some_logging_function_mostly_not_working_that_might_be_here_or_not()
        raise
    

    This will make it re-raise the exact exception. The main thing that you need to understand is that if there were a way to make all exceptions exit the system, you wouldn't be able to use a for loop (iterators raise a StopIteration exception).

0 comments:

Post a Comment