Python - Can I force exceptions to throw exceptions independently of try / except blocks?

In Python, is there any language (or interpreter) function to force the python interpreter to always throw exceptions, even if the code causing the violation is inside the try / except block?

I just inherited a large and old code base written in python, the purpose of which is to communicate with some specially designed hardware that we also developed. Many error messages and timeouts are masked / skipped due to the following (simplified) code template:

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

To avoid the typical “just rewrite everything from scratch” scenario, I'm currently trying to fix all the errors / exception timeouts. I do this by manually disabling all exception handling code, one at a time.

+5
source share
3 answers

The "all-exceptions" block except:is very bad, and you just need to find it and replace it with a reasonable one, except for processing.

In this case grep, your friend. A good IDE can help make these nasty things manageable.

But in Python there is no option to "ignore code as written".

+11
source

No, not at all. It's best to change the code to something more:

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

. , , , , for ( StopIteration).

+3

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
-2
source

All Articles