Ignore print statements when try catch exception - python

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:
Can someone explain why i still see the print statements even if i get an exception?
Is it possible to ignore print statements if the try-except catch an exception?

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)

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)

Related

Given error when trying to iterate through an exception

I am making a Reddit bot using PRAW and the code gives me the error that the exception is not iterable. Here is a simplification of my code:
try:
#something with praw that isn't relevant
except Exception as e: #this except error catches the APIexception, APIexpections in PRAW are a wide field of exceptions that dont't always have the same solution, so I scan the text for the error I'm looking for.
print(e)
if "keyword thats in the error" in e:
#fix the problem with the specific error
else:
print("Unkown APIExpection error")
This works fine for me, but when I run this code:
try:
#something
except Exception as e:
for character in e:
print(character)
#I also tried this
try:
#something
except Exception as e:
for character in str(e):
print(character)
#None of the above work but this is my actual code and what I need to do, anything that gets the above to work should work here too, I'm just letting you know this so that I don't get any other errors I have to ask another question for.
try:
#something
except Exception as e:
characterNum = 0
for character in e:
characterNum += 1
print(str(characterNum) + ": " + character)
It gives me a "TypeError: 'RedditAPIException' is not iterable", RedditAPIException can be ignore though as that's just the error I'm catching.
Convert the exception to string and then check in the if statement.
Change to => if "keyword thats in the error" in str(e):

Python code getting stuck while trying to handle an exception

Code:
def ScanNetwork():
nmScan = nmap.PortScanner()
s = nmScan.scan("192.168.1.1/24", '0-4444', arguments="-O")
for host in nmScan.all_hosts():
if nmScan[host].state() == "up":
print("Host : %s (%s)" % (host, nmScan[host].hostname()))
try:
print("Version: " + s['scan'][host]['osmatch'][0]['name'] + "\nType: " + s['scan'][host]['osmatch'][0]['osclass'][0]['type'])
except:
print("An Error occured while scanning this host!\nNo extra info was collected!")
continue
for proto in nmScan[host].all_protocols():
print("---------------------------")
print("\nProtocol : %s" % proto)
lport = nmScan[host][proto].keys()
lport = sorted(lport)
for port in lport:
print("\nport: " + f'{port}' + "\tstate: " + nmScan[host][proto][port]['state'])
print("---------------------------\n")
print("\n\nScan Completed!")
ScanNetwork()
Sometimes an exception occurs when the nmap fails to identify the Version or the Os running in a host. (It's a KeyError exception)
The part which is supposed to handle that exception is this:
try:
print("Version: " + s['scan'][host]['osmatch'][0]['name'] + "\nType: " + s['scan'][host]['osmatch'][0]['osclass'][0]['type'])
except:
print("An Error occured while scanning this host!\nNo extra info was collected!")
continue
I of course assume that there's nothing wrong with nmap's output and I've again made a huge beginner mistake and that's the reason my code is getting stuck..
Notes:
I've left the script running over night incase it returned some useful info but nothing happened!
Please do not tell me that I need to quit using the nmap module and turn to nmap3
Having tired you with all the above, does anyone know a way to still handle that exception without the code getting stuck?
You have forgotten to add the type of the exception to excpect while running the code inside the try-except block.
This should fix it:
try:
print("Version: " + s['scan'][host]['osmatch'][0]['name'] + "\n" + "Type: " + s['scan'][host]['osmatch'][0]['osclass'][0]['type'])
except KeyError:
print("An Error occured while scanning this host!\nNo extra info was collected!")
continue
In case you want to catch any possible exception that could occur (and yes custom ones included) then you should use the following code:
try:
<some critical code with possible exceptions to catch>
except Exception:
print("An exception occured")

Pass Exception to next except statement

I'm catching exceptions with a try...except block in Python. The program tries to create a directory tree using os.makedirs. If it raises WindowsError: directory already exists, I want to catch the exception and just do nothing. If any other exception is thrown, I catch it and set a custom error variable and then continue with the script.
What would theoretically work is the following:
try:
os.makedirs(path)
except WindowsError: print "Folder already exists, moving on."
except Exception as e:
print e
error = 1
Now I want to enhance this a bit and make sure that the except block for WindowsError only treats those exceptions where the error message contains "directory already exists" and nothing else. If there is some other WindowsError I want to treat it in the next except statement. But unfortunately, the following code does not work and the Exception does not get caught:
try:
os.makedirs(path)
except WindowsError as e:
if "directory already exists" in e:
print "Folder already exists, moving on."
else: raise
except Exception as e:
print e
error = 1
How can I achieve that my first except statement specifically catches the "directory already exists" exception and all others get treated in the second except statement?
Use one exception block and special case your handling there; you can just use isinstance() to detect a specific exception type:
try:
os.makedirs(path)
except Exception as e:
if isinstance(e, WindowsError) and "directory already exists" in e:
print "Folder already exists, moving on."
else:
print e
error = 1
Note that I'd not rely on the container-like nature of exceptions here; I'd test the args attribute explicitly:
if isinstance(e, WindowsError) and e.args[0] == "directory already exists":

Catching Error inside Else and Try

How to catch error inside "else" which that "else" inside "try".
Here is the code:
try:
if appcodex == app:
print "AppCode Confirmed"
if acccodex == acc:
print "Access Code Confirmed"
if cmdcodex == cmd:
print "Command Code Confirmed"
print "All Code Confirmed, Accessing URL..."
else:
print "Command Code not found"
else:
print "Access Code not found"
else:
print "AppCode not found"
except:
print "Error : Code doesn't match..."
How to raise "CommandCode not found" instead of "Error : Code doesn't match..." when cmdcodex/cmd has no input.
You'll need to create your own exception and raise it. Its as simple as creating a class that inherits from Exception, then using raise:
>>> class CommandCode(Exception):
... pass
...
>>> raise CommandCode('Not found')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.CommandCode: Not found
It is normal you get "Error : Code doesn't match..." instead of "Command Code not found". Why ? The answer is basic: you need to understand the basic concepts of handling exceptions in Python.In your special case, you must wrap that piece of code within a try .. except block also, like this:
try:
if appcodex == app:
print "AppCode Confirmed"
if acccodex == acc:
print "Access Code Confirmed"
try:
if cmdcodex == cmd:
print "Command Code Confirmed"
print "All Code Confirmed, Accessing URL..."
except:
print "Command Code not found"
else:
print "Access Code not found"
else:
print "AppCode not found"
except:
print "Error : Code doesn't match..."
To sum up the situation: you can nest as necessary try ... except blocks as you need. But you should follow this PEP

Exception in python unknown errors

except ValueError:
print "the input is Invaild(dd.mm.year)"
except as e:
print "Unknown error"
print e
This is the code I wrote, if an error different then valueerror will happen will it print it in e?
thanks
You'll need to catch the BaseException or object here to be able to assign to e:
except ValueError:
print "the input is Invaild(dd.mm.year)"
except BaseException as e:
print "Unknown error"
print e
or, better still, Exception:
except ValueError:
print "the input is Invaild(dd.mm.year)"
except Exception as e:
print "Unknown error"
print e
The blanket except: will catch the same exceptions as BaseException, catching just Exception will ignore KeyboardInterrupt, SystemExit, and GeneratorExit. Not catching these there is generally a good idea.
For details, see the exceptions documentation.
No, that code will throw a SyntaxError:
If you don't know the exception your code might throw, you can capture for just Exception. Doing so will get all built-in, non-system-exiting exceptions:
except ValueError:
print "the input is Invaild(dd.mm.year)"
except Exception as e:
print "Unknown error"
print e

Categories