Reputation:
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.
Upvotes: 5
Views: 2434
Reputation: 107
I guess you want to ignore except especially when you are debugging and apply it otherwise.
One good way is to have a global variable say debug=True and conditionally invoke raise:
debug=True
def foo:
try:
# do some code
except:
if debug: raise #put this in all excepts
Now set debug to False whenever raise is to muted all across
Upvotes: 0
Reputation: 391952
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.
Upvotes: 11
Reputation: 198707
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).
Upvotes: 3
Reputation: 10351
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
Upvotes: -2