Catching Error inside Else and Try - python

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

Related

python catching "all other error" type example case

In the code below when I ran it it suppose to catch all error with "except Exception as error:" return " Not possible" but thats
not the case when I set mystery_value = a it gives me a NameError. I don't understand this could someone help explain? Thanks.
mystery_value = a
try:
print(10/mystery_value)
except ZeroDivisionError as error:
print("Can't divide by zero")
except Exception as error:
print("Not possible")
it's because the error occurs before the try except block. it occurs at the first line because a doesn't refer to anything and it doesn't run reach the try except. if you replaced a with 'a' the exception would work.
mystery_value = 'a' # replace a with 'a'
try:
print(10/mystery_value)
except ZeroDivisionError as error:
print("Can't divide by zero")
except Exception as error:
print("Not possible")
output
Not possible

Python - While True: Try Except Else - Program Flow Question

I have this code using a While True with a try catch. The final else statement is always being executed when the 'try' is successful and I'd like to understand why - I think I'm not understanding the program flow correctly.
while True:
try:
subprocess.call(["wget", "-O", "splunk-8.0.1-6db836e2fb9e-Linux-x86_64.tgz", "https://www.splunk.com/bin/splunk/DownloadActivityServlet?architecture=x86_64&platform=linux&version=8.0.1&product=splunk&filename=splunk-8.0.1-6db836e2fb9e-Linux-x86_64.tgz&wget=true"])
print("successfully downloaded splunk enterprise")
time.sleep(2)
except OSError as e:
if e.errno == 2:
print(e)
print("wget doesn't seem to be installed")
time.sleep(2)
print("attempting to install wget")
time.sleep(2)
subprocess.call(["yum", "install", "wget"])
else:
print(e)
print("unknown error response, exiting...")
break
else:
print("something else went wrong while trying to download splunk")
break
based on python documentation, try-except can take an optional else statement:
The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.
so based on this, your else statement will run if codes in try doesn't raise any exception!
what you want is another except clause that catches a general exceptation, so you just need to replace else with except:
while True:
try:
subprocess.call(["wget", "-O", "splunk-8.0.1-6db836e2fb9e-Linux-x86_64.tgz", "https://www.splunk.com/bin/splunk/DownloadActivityServlet?architecture=x86_64&platform=linux&version=8.0.1&product=splunk&filename=splunk-8.0.1-6db836e2fb9e-Linux-x86_64.tgz&wget=true"])
print("successfully downloaded splunk enterprise")
time.sleep(2)
except OSError as e:
if e.errno == 2:
print(e)
print("wget doesn't seem to be installed")
time.sleep(2)
print("attempting to install wget")
time.sleep(2)
subprocess.call(["yum", "install", "wget"])
else:
print(e)
print("unknown error response, exiting...")
break
except:
print("something else went wrong while trying to download splunk")
break
The else clause of a try executes if the code inside the try did not throw an exception. If you want to catch any exception, use except without specifying an exception class:
except:
print("something else went wrong while trying to download splunk")
break
However, consider just omitting this piece of code. As it is currently written, it doesn't tell you what went wrong. If you remove these lines, you will get an error message that tells you what happened and on which line the error occurred.
From here:
The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.
So the else clause will run if the code within the try block runs successfully.

Python Try with some Additional Logic

Hello I am trying to make 'try' only work under one condition:
try:
print "Downloading URL: ", url
contents = urllib2.urlopen(url).read()
except:
message = "No record retrieved."
print message
return None
I do not want the above code to work if the kwarg nodownload is True.
So I have tried the following:
try:
if nodownload:
print "Not downloading file!"
time.sleep(6)
raise
print "Downloading URL: ", url
contents = urllib2.urlopen(url).read()
except:
message = "No record retrieved."
print message
return None
The above always downloads no matter if the --nd argument is passed in the command line. The below always skips the file rather the argument is passed or not.
if not nodownload:
print "Not downloading file!"
time.sleep(6)
raise
print "Downloading URL: ", url
contents = urllib2.urlopen(url).read()
except:
message = "No record retrieved."
print message
return None
No download is input at the command line:
parser.add_argument('--nodownload', dest='nodownload', action='store_true',
help='This doesn't work for some reason')
You can use raise to cause an exception when you need to, thus making the try fail.
As others have mentioned, one can raise an exception.
Apart from using predefined exceptions, you may also use your own:
class BadFriend(Exception):
pass
class VirtualFriend(Exception):
pass
class DeadFriend(Exception):
pass
try:
name = raw_input("Tell me name of your friend: ")
if name in ["Elvis"]:
raise DeadFriend()
if name in ["Drunkie", "Monkey"]:
raise BadFriend()
if name in ["ET"]:
raise VirtualFriend()
print("It is nice, you have such a good friend.")
except BadFriend:
print("Better avoid bad friends.")
except VirtualFriend:
print("Whend did you shake hands with him last time?")
except DeadFriend:
print("I am very sorry to tell you, that...")
You can even pass some data via raised exception, but be careful not to abuse it too far (if
standard structures are working, use simpler ones).

Exceptions and sqlite3

import sqlite3
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO loctions VALUES('Hogwarts', 'Scotland'")
cursor.execute("INSERT INTO characters VALUES('Albus', 'Dumbledore')")
conn.commit()
except sqlite3.OperationalError:
print "Oops! This was an operational error. Try again..."
except sqlite3.NameError:
print "Name Error"
except sqlite3.ValueError:
print "value error"
except sqlite3.IOError:
print "IO error"
conn.close()
I'm trying to figure out if the above is valid code. That is, can I have multiple exceptions after my "try" clause?
When I ran this by typing 'python filename.py', I saw "Oops! This was an operational error. Try again..." printed in my terminal.
This made sense because I had spelled the name of the first table wrong (loctions instead of locations), so it was an Operational Error.
But I'm confused about how to force a Name Error or a Value Error.
Also, when I commented out the "except sqllite3.OperationalError" clause, I got this error in my terminal:
Traceback (most recent call last):
File "sqle.py", line 14, in <module>
except sqlite3.NameError:
AttributeError: 'module' object has no attribute 'NameError'
Is this saying that there's no such thing as sqlite3.NameError? Yet sqlite3.OperationalError is a thing.
How do I discover what types of errors there are?
NameError, ValueError, IOError are builtin exceptions. Don't qualify them with sqlite3.:
...
except NameError:
print "Name Error"
except ValueError:
print "value error"
except IOError:
print "IO error"
To see which exceptions are defined in the module (using the property that exceptions are subclass of the Exception class):
>>> import inspect
>>> [name for name, value in vars(sqlite3).items()
if inspect.isclass(value) and issubclass(value, Exception)]
['Warning', 'InternalError', 'ProgrammingError', ..., 'OperationalError']
Or consult the module documentation

Ignore print statements when try catch exception

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)

Categories