Python: pseudo try before actually try and finding exception - python

I know I'm not clear on this thing but I couldn't be more specific in the title. Consider the following code:
try:
print "Try this out"
a = int("Blah blah")
except:
print "I got the exception"
The output of this code is-
Try this out
I got the exception
What I want the python to do is to check if it might raise an exception in the try: block first and then execute it. Else, just execute the except: block. Is it possible to do such a thing without nesting the multiple try-except blocks.

No, it's not possible, because you get an exception during execution. But you can do like this:
try:
a = int("Blah blah")
print "Try this out"
except:
print "I got the exception"

Your try statement prints up as no error happens in printing it ,but as soon as it tries to execute a, gets an error so except executes.
Try this way to catch the exception properly:
try:
a = int("Blah blah")
print ("Try this out")
except:
print ("I got the exception")

Related

What should i put into the exeption block and why It can't be bare?

I got my little voice assistant in python, but I don't know what to do if wolframalpha doesn't give me any answer back.
elif 'wolfram' in command:
try:
print("I can answer your questions")
talk("I can answer your questions")
question = take_command()
app_id = "XXXXXXXXXXXX"
client = wolframalpha.Client(app_id)
res = client.query(question)
answer = next(res.results).text
print(answer)
except:
print("Sorry, I can't answer that")
talk("Sorry, I can't answer that")
It gives me these warnings
PEP 8: E722 do not use bare 'except'
Too broad exception clause
That is just a linter warning. To avoid it you can swallow the exception explicitly: remove the try...except block and run the code to find out what exception is being thrown, then catch it:
try:
# ...code...
except NoAnswerException as ex: # Or whatever is being thrown
# ...handle exception gracefully
If you really want a catch-all, you can do except Exception as ex:. Note also that usually you want to have as little code as possible in the try block (ideally just one line) so you know which exceptions can be thrown and catch them explicitly.

having problems with python error handlers

hello I am pretty new into python , but I am trying to handle errors, however when I try to ctrl + C or L I got input > ^Cerror which it should be only display error and not ^C or ^L how can I fix this ?
except KeyboardInterrupt:
print("error")
except Exception as e:
raise e
You can back up and overwrite it, but you can't "fix" it. That character comes from the keyboard echo of the symbiont terminal: your stdin processor is set to echo (print to screen) whatever is typed. That ^C couplet is printed by this I/O processing before your program gets to handle the exception. Thus, the \r option (or a sequence of backspaces, \b) is likely your best remedy.
import sys
try:
while True:
string = input("Show me something")
except KeyboardInterrupt:
print("\b\b error")
except Exception as e:
raise e
Output, with CTRL-C at keyboard:
Show me something error
If you want to wipe out the entire input line, use \r instead:
except KeyboardInterrupt:
print("\rerror", " "*80)
Output:
Show me something -- this line appears until I hit CTRL-C. Replaced by
error

Handling Exceptions in Arduino-Python Communications

I am trying to implement a system where outputs from an Arduino can be passed on to and printed in Python.
I have the following Arduino code snippet below:
void loop() {
if (Serial.available()) {
c = Serial.read();
if (c == '1') {
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, LOW);
//Serial.print("1 ON, 2 OFF\n");
}
My Python code snippet is as follow:
import serial
import time
arduino = serial.Serial('COM3', 9600, timeout=1)
msg = arduino.readline(arduino.inWaiting()) # read everything in the input buffer
time.sleep(3)
ASCIIdata = '121210'
for i in range(len(ASCIIdata)):
if ASCIIdata[i] == '1':
strin = '1'
arduino.write(strin.encode())
time.sleep(0.2)
#print(ASCIIdata[i])
try:
print ("Message from arduino: ")
print arduino.readline()
raise
except Exception as e:
print ("Fail to send!")
In the above example, I am trying to send inputs to Arduino via ASCIIdata, and when it matches the if-statement in Arduino, commands in the if-statement will be executed. I have purposely not do a print in Arduino and attempt to read something from Python by doing:
try:
print ("Message from arduino: ")
print arduino.readline()
raise
except:
print ("Fail to send!")
I observed that if I do not put raise in the try statement, the except statement will not be executed, but the program moves on after the specific timeout. Hence, I put raise in the try statement. May I ask if this is the correct approach to raising an exception?
I read that I should be doing except Exception as e instead of doing except because I would be catching all kinds of exception while the program is running. May I ask if this thought process is correct?
First of all, I'm not very much into Python, so I'm not really sure, but having experience in other languages I think that this answer is correct.
What you did is... wrong. You don't want to raise an exception every time.
Looking at the documentation of the readline function,
readlines() depends on having a timeout and interprets that as EOF
(end of file). It raises an exception if the port is not opened
correctly.
This means that a timeout does not raise exceptions. You can test if the buffer is empty:
try:
print ("Message from arduino: ")
buff = arduino.readline()
print buff
if not buff:
raise
except:
print ("Fail to send!")
Even if you may just skip the exception:
print ("Message from arduino: ")
buff = arduino.readline()
print buff
if not buff:
print ("Fail to send!")
If you prefer another behavior, write your own function (for instance this answer has something which looks like a reading function; you'll just have to add the exception raising.
As for the type of exception, usually it is best to use just one type of exception, in order to avoid catching everything. For instance:
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
try:
raise MyError(2*2)
except MyError as e:
print 'My exception occurred, value:', e.value
To answer your first question, this is the correct way to catch exceptions. The caveat is that you need to know what exceptions the code inside the try block raises. In your case arduino.readline() will only raise an exception on a serial port issue. In other words you don't need to call raise yourself because that means it will always look like a failure.
Using except Exception as e allows you to handle specific exceptions that code in the try block might raise. This way you can respond in different ways.
For example you might have different response for different errors:
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise

Break statement in finally block swallows exception

Consider:
def raiseMe( text="Test error" ):
raise Exception( text )
def break_in_finally_test():
for i in range(5):
if i==2:
try:
raiseMe()
except:
raise
else:
print "succeeded!"
finally:
print "testing this!"
break
if __name__=='__main__':
break_in_finally_test()
I expected to see Exception( "Test error" ) to be raised, but instead only "testing this" is printed. The intention, of course, was to call raiseMe() only once, no matter if we succeed or not - but if it raises an exception, I would have wanted to see that!
Why does break swallow the exception that I explicitly raise?
From https://docs.python.org/2.7/reference/compound_stmts.html#finally:
If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. If the finally clause raises another exception or executes a return or break statement, the saved exception is discarded
This also reflects the behaviour expected from the try...finally statement before PEP341:
This is how a try except finally block looked like pre PEP341:
try:
try:
raiseMe()
except:
raise
finally:
#here is where cleanup is supposed to happen before raising error
break
#after finally code: raise error
As the raising of errors never happens in the finally block it is never actually raised.
To maintain backwards compatibility with Python<=2.4, it had to be done in this way.
From the docs Error Handling Docs:
A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.
Your exception never gets raised because you break before the try statement gets fully evaluated.
I think upon reflection that it is due to the fact that break actually raises a StopIteration to "break" out of the for-loop. This is really not very intuitive and not particularly well documented (not mentioned on 1, for example). Could maybe someone confirm/explain it better?
Have the following code structure:
def func():
try:
driver.do("something")
except TimeoutException:
pass
finally:
result = driver.do("something else")
return result
Got the exception by pylint:
return statement in finally block may swallow exception (lost-exception)
Solution was to put return out of the finally statement:
def func():
try:
driver.do("something")
except TimeoutException:
pass
finally:
result = driver.do("something else")
return result # <<

Python: rasing from except causes finally to execute?

Say I have the following code:
try:
[...]
except:
raise Exception([...])
finally:
[code]
My question is: if the code in the try block raises an exception which is caught in except, is [code] from the finally clause executed since a new exception is raised in the except clause? And if so, when is it executed? Before the new exception is raised or after the new exception is propagated through the method stack?
an example is worth a 1000 words, why didn't you just try what you've written?
>>> def foo():
>>> try:
>>> print "2 try block"
>>> raise Exception("1")
>>> print "never printed"
>>> except:
>>> print "3 first except block"
>>> raise Exception("2")
>>> finally:
>>> print "4 finally block"
>>> print "end of function"
>>>
>>> try:
>>> print "1 before foo"
>>> foo()
>>> print "never printed too"
>>> except:
>>> print "5 outter except clause"
1 before foo
2 try block
3 first except block
4 finally block
5 outter except clause
Before the new exception is raised or after the new exception is propagated through the method stack?
so as you can tell from the example, the finally block is called after the except block it has been defined in (i.e. after leaving the try/except/finally block), but before getting to the outer try/except block.
Which is logical, you want the finally to always be triggered when you exit the try block however you exit it, so you can be sure that your code environment is coherent when executing code outside of the try statement (whether you're releasing resources, or resetting values, or rolling back/committing modifications...).
finally is executed no matter the try block succeeds or the except block is run due to exceptions!
even if your except block raises an exception the new exception will be handled by another try catch handler but after executing the finally block, instead of forming a recursive loop:
try:
try:
[...]
except:
raise Exception([...]) #this is line number xyz
finally:
[code]
except:
[...] #this code will be running after line number xyz

Categories