-3

I have some code which represents a test case within a proprietary testing framework that looks something like this:

def test_alarm(self):
    self.setup_some_test_data()
    try:
        self.send_alarm_message()
    except:
        print "Unexpected error:", sys.exc_info()
    finally:
        self.teardown_some_test_data()

I've been told to drop the print as it's not necessary and the test framework will in any case catch any exceptions, which is preferred to catching them here, but I still need to always clear the data down, as in the finally block.

Do I just drop the except block entirely? Alternatively, how, can I structure the code to effectively have an empty except block and retain the finally? Is this good practice in Python or is there a better way to do it?

Edit Note that I did try just dropping the except block entirely, and I had no obvious run-time problems, though since exceptions are unlikely in the the call to send_alarm_message(), it was unclear to me how it would work if an exception was thrown or whether this was considered good practice by the Python community.

Component 10
  • 10,247
  • 7
  • 47
  • 64
  • 1
    *"Do I just drop the `except` block entirely?"* - why didn't you try it? – jonrsharpe Jul 17 '15 at 09:25
  • @jonrsharpe I did try it, and I had no obvious run-time problems, though since exceptions are unlikely, it was unclear to me how it would work if an exception was thrown or whether this was considered good practice by the Python community. – Component 10 Jul 17 '15 at 09:58
  • 1
    Note that some of the examples [in the documentation](https://docs.python.org/2/reference/compound_stmts.html#the-try-statement) don't include `except`. – jonrsharpe Jul 17 '15 at 10:00

3 Answers3

2

Either drop the except Block, or improove it really by adding

except [Exception-Class]:
    pass

where [Exception-Class] is the exception to be excepted. This adds some sugar on it, because really unexpected Errors are not getting catched by this. (Or add this as a seperate:

except Exception, ex:
    print "Unexpected error:", ex
1

If you don't want to do anything in except block, then you can pass it.

try:
    self.send_alarm_message()
except:
    pass
finally:
    self.teardown_some_test_data()
Sudipta
  • 4,773
  • 2
  • 27
  • 42
1

Yes, you can drop the except block completely, it is a valid python syntax to have just try and finally . Example -

In [58]: try:
   ....:     print("Blah")
   ....: finally:
   ....:     print("halB")
   ....:
Blah
halB

Please note this will not catch any Exceptions/Errors that occur within the try block, and I am guessing that is what you want.

I have seen this used at quite some places, where we are creating some variables/resources that need to be cleared irrespective of whether any exceptions/errors occur, but we do not want to handle any Exceptions at that particular place.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176