Say I have the following code:
try: print 'foo' # A lot more code... print 'bar' except: pass
How would I for testing purposes disable the try-statement temporary?
You can't just comment the try
and except
lines out as the indention will still be off.
Isn't there any easier way than this?
#try: print 'foo' # A lot more code... print 'bar' #except: # pass
In case that you are using an if statement inside a try , you are going to need more than one sys. exit() to actually exit the program. otherwise, you want to use one try-except block for each evaluation.
Python3. Now it is clearly seen that the exception handler ( try/except) is comparatively faster than the explicit if condition until it met with an exception. That means If any exception throws, the exception handler took more time than if version of the code.
You could reraise the exception as the first line of your except block, which would behave just as it would without the try/except.
try:
print 'foo'
# A lot more code...
print 'bar'
except:
raise # was: pass
Piggy-backing off of velotron's answer, I like the idea of doing something like this:
try:
print 'foo'
# A lot more code...
print 'bar'
except:
if settings.DEBUG: # Use some boolean to represent dev state, such as DEBUG in Django
raise # Raise the error
# Otherwise, handle and move on.
# Typically I want to log it rather than just pass.
logger.exception("Something went wrong")
Turn it into an if True
statement, with the except
clause 'commented out' by the else
branch (which will never be executed):
if True: # try:
# try suite statements
else: # except:
# except suite statements
The else:
is optional, you could also just comment out the whole except:
suite, but by using else:
you can leave the whole except:
suite indented and uncommented.
So:
try:
print 'foo'
# A lot more code...
print 'bar'
except SomeException as se:
print 'Uhoh, got SomeException:', se.args[0]
becomes:
if True: # try:
print 'foo'
# A lot more code...
print 'bar'
else: # except SomeException as se:
print 'Uhoh, got SomeException:', se.args[0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With