Question

I have this simple try-except code:

self.tf.router.EchoProg(state=1)
try:
    print "\tCheckTestFirmwareCommunication_SetPort: "  
    print self.tf.DUT.CheckTestFirmwareCommunication_SetPort()
except NoResponseException, e:
    print "\tCheckTestFirmwareCommunication_SetPort: ", repr(e)
self.tf.router.EchoProg(state=0)

Output with Exception:

CheckTestFirmwareCommunication_SetPort:
CheckTestFirmwareCommunication_SetPort: DD_NoResponseException()

Questions:

  1. Can someone explain why i still see the print statements even if i get an exception?

  2. Is it possible to ignore print statements if the try-except catch an exception?

Was it helpful?

Solution

It is the second print line that throws the exception:

print self.tf.DUT.CheckTestFirmwareCommunication_SetPort()

The first print line did not and was executed.

Python executes each statement within the try suite, and only when one throws an exception, is execution aborted and transfers to the except block. If you don't want the first print statement to execute when CheckTestFirmwareCommunication_SetPort throws an exception, call that method first:

self.tf.router.EchoProg(state=1)
try:
    port = self.tf.DUT.CheckTestFirmwareCommunication_SetPort()
    print "\tCheckTestFirmwareCommunication_SetPort: "  
    print port
except NoResponseException, e:
    print "\tCheckTestFirmwareCommunication_SetPort: ", repr(e)
self.tf.router.EchoProg(state=0)

OTHER TIPS

The first print statement is executed before the exception occurs, hence they are printed.

The exception here is raised by self.tf.DUT.CheckTestFirmwareCommunication_SetPort(). You can move the print statements below it, so that it'll be printed when the first line is successfully executed.

try:
    print self.tf.DUT.CheckTestFirmwareCommunication_SetPort()
    print "\tCheckTestFirmwareCommunication_SetPort: "  
except NoResponseException, e:
    print "\tCheckTestFirmwareCommunication_SetPort: ", repr(e)

The thing is that exception is raised by the line:

print self.tf.DUT.CheckTestFirmwareCommunication_SetPort()

so the line:

print "\tCheckTestFirmwareCommunication_SetPort: "  

always will by executed.

to avoid that change your code to:

self.tf.router.EchoProg(state=1)
try:

    port =  self.tf.DUT.CheckTestFirmwareCommunication_SetPort()
except NoResponseException, e:
    print "\tCheckTestFirmwareCommunication_SetPort: ", repr(e)
else:
    print "\tCheckTestFirmwareCommunication_SetPort: ", port  
self.tf.router.EchoProg(state=0)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top