I made a program that takes values from treeview and calculate something when button is pressed. I put try / except statement inside that function.
def SumAll():
try:
#do something (calculate)
except ValueError:
Error=messagebox.showinfo("Enter proper values")
pass
The problem is, program keeps running when messagebox.showinfo appears, and it gives the ValueError.
How can I fix that, and how can I put more than one error exception (IndexError, etc)?
You can re-raise the exception, and if the exception reaches the top of the stack, the program will exit
try:
#do something (calculate)
except ValueError:
Error=messagebox.showinfo("Enter proper values")
raise
Or you can manually call sys.exit
import sys
try:
#do something (calculate)
except ValueError:
Error=messagebox.showinfo("Enter proper values")
sys.exit(1)
To catch more than on in the same handler, you can do something like
try:
#do something (calculate)
except (IndexError, ValueError):
Error=messagebox.showinfo("Enter proper values")
raise
or if you want different handlers you can have
try:
#do something (calculate)
except IndexError:
Error=messagebox.showinfo("Some message")
raise
except ValueError:
Error=messagebox.showinfo("Enter proper values")
raise
You can catch multiples by:
try:
k = input().split()[2]
i = int(k[0])
except (IndexError, ValueError) as e:
print(e) # list index error: 'Hello World', Value error: 'Hello World Tata'
else:
print("no error")
this will guard against inputs that split to less then 3 items '5 a' as well as against int conversion errors: 'Hello World Is A Cool Thing' (`'Is'`` is not an integer).
Use How to debug small programs (#1) to debug through your real program, the error you get above this except is caught. You probably get a resulting error somewhere else because somethings not right with the return of your function.
Related
I'm trying to exit a script from inside a try: except: block except it just goes on to the exception case.
None of these...
try:
exit()
except:
pass()
try:
quit()
except:
pass
import sys
try:
sys.exit()
except:
pass
...exit my script, they just go on to the except case.
How would I exit my script from inside one of these blocks?
All of these examples raise the SystemExit exception and you are catching that exception, a blank except clause will catch all exceptions.
This is the reason why you should always specify the exception you intend to catch or at least use except Exception eg
try:
exit()
except Exception:
pass
try:
quit()
except Exception:
pass
import sys
try:
sys.exit()
except Exception:
pass
With that change in place, all of you examples will cause your Python app to exit
I have a script that catches all exceptions, which works great unless I want to abort the script manually (with control + c). In this case the abort command appears to be caught by the exception instead of quitting.
Is there a way to exclude this type of error from the exception? For example something as follows:
try:
do_thing()
except UserAbort:
break
except Exception as e:
print(e)
continue
You could just force to exit the program whenever the exception happens:
import sys
# ...
try:
do_thing()
except UserAbort:
break
except KeyboardInterrupt:
sys.exit()
pass
except Exception as e:
print(e)
continue
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
This function is supposed to catch exceptions in the main execution. If there is an exception it should print out the error with log.error(traceback.print_exc()) and clean up with exit_main().
def main():
try:
exec_app()
except KeyboardInterrupt:
log.error('Error: Backup aborted by user.')
exit_main()
except Exception:
log.error('Error: An Exception was thrown.')
log.error("-" * 60)
log.error(traceback.print_exc())
log.error("-" * 60)
exit_main()
Unfortunately log.error(traceback.print_exc()) does only return None if there is an exception. How can I make traceback print the full error report in this case?
PS: I use python 3.4.
From its __doc__:
Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'
That is, it isn't supposed to return anything, its job is to print. If you want the traceback as a string to be logged, use traceback.format_exc() instead.
I usually use traceback.print_exc() just for debugging. In your case, to log your exception you can simply do the following:
try:
# Your code that might raise exceptions
except SomeSpecificException as e:
# Do something (log the exception, rollback, etc)
except Exception as e:
log.error(e) # or log(e.message) if you want to log only the message and not all the error stack
Try:
#some statement
Try:
#some statement
Except:
#statement1
Raise exception()
#statement2
Except: #some statement
Can I pass the control like the above code in python., will the inner except pass the control to the outer except and will the #statement2 be executed?
This code will answer your question:
#!/usr/bin/env python
import sys
try:
try:
raise Exception("first exception")
except Exception as e:
print e.message
raise Exception("second exception")
print "second statement" # never printed - 'dead code'
except Exception as e:
print e.message
Both except blocks are executed but the statement after raising the second exception is not.
Generally you should know that once an exception is raised, nothing executes until it is caught by an except block that is relevant to this exception or any superclass of it.