Alright, so I've got a try and except block watching out for exceptions.
This is all normal but when you've got a loop you can't stop the code usually, as there's no specific bit saying "Don't catch KeyboardInterrupt errors" or something alike
Is there anything that let's try and except blocks exclude specific errors? (or an alternative)
My code
while 1:
if ques == 'n':
try:
newweight = int(input('Please enter a number'))
exit()
except:
print('Please enter a valid number')
Now this will create an infinite loop as the "exit()" will not happen as it will get raised an as exception, and it will thus create an infinite loop. Is there any way for this to not happen?
To prevent a user entering a non-integer value, you want to catch a TypeError so you can change except: to except ValueError: and it will then catch any invalid inputs. That should cover you sufficiently.
Related
I've run into a bug where the program seems to think that my input into an input statement isn't within the parameters, when it clearly is.
This is the code i'm having trouble with:
time.sleep(1.5)
print()
print()
print("You have chosen", horsechoice)
time.sleep(1)
print("How much do you want to bet?")
while True:
try:
moneyinput = int(input())
racebegin(moneyinput)
break
except:
print("Not a valid amount of money.")
continue
Even when I input an integer, it still states that I didn't input a valid amount of money.
If you only want to check the input validity, you should wrap the try/except only around the int(input()) call, not racebegin(). Your code is probably catching an error in racebegin().
It's also a good idea to narrow down the type of error you're catching with except:. Doing that might have prevented the problem in the original code, unless racebegin() was also raising ValueError.
while True:
try:
moneyinput = int(input())
break
except ValueError:
print("Not a valid amount of money.")
racebegin(moneyinput)
Here is the code
while True:
try:
age = int(input("Enter your age"))
except ValueError:
print("Enter the age in integer")
continue
except ZeroDivisionError: #when trying to divide the age for an age groups
print("Age cannot be zero")
continue
else:
print("thank you!!")
break
finally:
print("ok! I am finally done")
In the input, for age I give a string (eg: wefervrsvr) so it must go through the ValueError in the except block which has print function and then continue statement that makes the control of the program to the top in the loop so it asks for input again from us, but the thing I don't understand here is that why does finally executes before the control jumps to try block at the top as I see in the output.
From the python docs:
When a return, break or continue statement is executed in the try suite of a try...finally statement, the finally clause is also executed ‘on the way out'.
'on the way out' basically means, if a continue statement is executed inside of an exception clause, the code in the finally clause will be executed and then the loop will continue on to the next iteration.
The finally block exists to guarantee you can execute some code, regardless of what happens in the try block. The continue keyword will not circumvent it and even an unhandled exception will not circumvent it.
If you removed that catch of the ValueError, for example, you will still hit the finally block:
try:
raise ValueError("unhandled exception type");
except ZeroDivisionError:
print("problems.")
finally:
print("will print, even in the face of an unhandled exception")
A decent answer for this
import time;
while True:
try:
print("waiting for 10 seconds...\n")
continue
print("never show this")
finally:
print("Finally starts executing\n");
time.sleep(10)
print("\nFinally ends executing control jumps to start of the loop");
try:
float(self.entry_weight.get()) and int(self.entry_height.get())
self.get_bears()
except:
messagebox.showinfo("Number Error","Your weight and height must be a number!")
Hello,
This try/except statement doesn't seem to be working, when I input numbers into the entry boxes, and click the associated button, I only get the message box saying that my inputs are not numbers.
I have used print statements to make sure I am testing the right entry boxes and i am. When i test the type i get back as expected but surely if these string inputs are numbers, the try except statement should work. Any help would be great thanks.
Your try/except block covers too much territory. In addition to problems with input, it catches everything that could go wrong with get_bears. Additionally, and short-circuits so the second check is never made if weight is 0. You can use two try/except blocks to cover everything
try:
# validate input
float(self.entry_weight.get())
int(self.entry_height.get())
except ValueError:
messagebox.showinfo("Number Error","Your weight and height must be a number!")
return
try:
self.get_bears()
except:
messagebox.showinfo("Unhandled Error","Unknown error in program")
# log it somewhere
import traceback
traceback.print_exc()
# likely want to exit() because program is highly busted
I'm in trouble about how to end a 'try' loop, which is occurred since I have the 'try', here is the code:
import time
class exe_loc:
mem = ''
lib = ''
main = ''
def wizard():
while True:
try:
temp_me = input('Please specify the full directory of the memory, usually it will be a folder called "mem"> ' )
if temp_me is True:
exe_loc.mem = temp_me
time.sleep(1)
else:
print('Error value! Please run this configurator again!')
sys.exit()
temp_lib = input('Please specify the full directory of the library, usually it will be a folder called "lib"> ')
if temp_lib is True:
exe_loc.lib = temp_lib
time.sleep(1)
else:
print('Invalid value! Please run this configurator again!')
sys.exit()
temp_main = input('Please specify the full main executable directory, usually it will be app main directory> ')
if temp_main is True:
exe_loc.main = temp_main
time.sleep(1)
I tried end it by using break, pass, and I even leaves it empty what I get is Unexpected EOF while parsing, I searched online and they said it is caused when the code blocks were not completed. Please show me if any of my code is wrong, thanks.
Btw, I'm using python 3 and I don't know how to be more specific for this question, kindly ask me if you did not understand. Sorry for my poor english.
EDIT: Solved by removing the try because I'm not using it, but I still wanna know how to end a try loop properly, thanks.
Your problem isn't the break, it's the overall, high-level shape of your try clause.
A try requires either an except or a finally block. You have neither, which means your try clause is never actually complete. So python keeps looking for the next bit until it reaches EOF (End Of File), at which point it complains.
The python docs explain in more detail, but basically you need either:
try:
do_stuff_here()
finally:
do_cleanup_here() # always runs, even if the above raises an exception
or
try:
do_stuff_here()
except SomeException:
handle_exception_here() # if do_stuff_here raised a SomeException
(You can also have both the except and finally.) If you don't need either the cleanup or the exception handling, that's even easier: just get rid of the try altogether, and have the block go directly under that while True.
Finally, as a terminology thing: try is not a loop. A loop is a bit of code that gets executed multiple times -- it loops. The try gets executed once. It's a "clause," not a "loop."
You have to also 'catch' the exception with the except statement, otherwise the try has no use.
So if you do something like:
try:
# some code here
except Exception:
# What to do if specified error is encountered
This way if anywhere in your try block an exception is raised it will not break your code, but it will be catched by your except.
I am having some trouble understanding ways to use the "except" statement in Python. I am a horrendous coder right now, so my apologies in advance.
Here is the small code I am trying to run:
def mathWorks():
print " Answer the following: 5 + x = 10"
x = int(raw_input("Please type your answer: "))
if x == 5:
print "You are correct!"
else:
print "You are incorrect!"
break
except ValueError:
print "That is not an integer!"
mathWorks()
I think what I am trying to accomplish is pretty self explanatory. Unfortunately I am getting an "invalid syntax" for the "except" statement in this code.
What all am I doing wrong here?
except has to come after a try block. This signals the section of code that should have the exception handled:
try:
x = int(raw_input("Please type your answer: "))
except ValueError:
print "That is not an integer!"
Read it as 'try this, then do this if it fails'. Note it's good practice to do as little as possible in the try block - this ensures you don't catch errors you don't mean to (as does specifying the type of exception to catch, which you were already doing).
In this case, you might want to call sys.exit(1) in the except block as well, otherwise the program will continue (and fail with another error).
It's used like this:
try: # try code here
except: # except errors here
For your code, there is a "else" statement, you should use "else" statement after all of your except statements.
This is not directly related to your question, but you may encounter this further down.
Please refer to the original document for more details:
https://docs.python.org/2/tutorial/errors.html