Reputation: 1
I'm having a problem with a program where it runs the exception along with the try command and I don't know what to do since it prints the conversion and the error message.
def main():
print('What would you like to convert?')
print('1. Miles to Kilometers')
print('2. Fahrenheit to Celcius')
print('3. Gallons to Liters')
print('4. Pounds to Kilograms')
print('5. Inches to Centimeters')
try:
option = int(input('Menu Option:'))
if option == 1:
Inptmiles = float(input('Enter number of miles to convert:'))
milestokm(Inptmiles)
usercontinue()
if option == 2:
InptFrnht = float(input('Enter degrees that you would like to convert:'))
FrnhttoClcs(InptFrnht)
usercontinue()
if option == 3:
InptGllns = float(input('Enter number of Gallons you would like to convert:'))
GllnstoLtrs(InptGlls)
usercontinue()
if option == 4:
InptLbs = float(input('Enter number of pounds you would like to convert:'))
LbstoKgs(InptLbs)
usercontinue()
if option == 5:
InptInches = float(input('Enter number of Inches you would like to convert:'))
InchestoCm(InptInches)
usercontinue()
except:
print('Sorry there was an error with your input')
def milestokm(miles):
convkm = miles * 1.6
print(f'{miles} Miles is equal to {convkm:.2f} Kilometers')
def FrnhttoClcs(Fahrenheit):
convClcs = (Fahrenheit - 32) * 5/9
print(f'{Fahrenheit} Degrees Fahrenheit is equal to {convClcs:.2f} Degrees Celcius')
def GllnstoLtrs(Gallons):
convLtrs = Gallons * 3.9
print(f'{Gallons} Gallons is equal to {convLtrs:.2f} Liters')
def LbstoKgs(Pounds):
convKgs = Pounds * 0.45
print(f'{Pounds} Pounds is equal to {convKgs:.2f} Kilograms')
def InchestoCm(Inches):
convCm = Inches * 2.54
print(f'{Inches} Inches is equal to {convCm:.2f} Centimeters')
main()
I tried moving the exception down past the define commands that used the stored variables but it came back as an error.
Upvotes: -3
Views: 87
Reputation: 36
An error is raised because name 'usercontinue' is not defined
.
To find the error, I used this snippet of code:
except Exception as e:
print(e)
Upvotes: 1
Reputation: 31379
This is exactly why you should never just use try ... except ...
without specifying a specific exception. If you re-raise the exception, you'll find that the issue is a missing definition:
except Exception as e:
print('Sorry there was an error with your input')
raise e
Output will be something like:
...
Sorry there was an error with your input
Traceback (most recent call last):
File "<path>\main.py", line 60, in <module>
main()
File "<path>\main.py", line 32, in main
raise(e)
File "<path>\main.py", line 13, in main
usercontinue()
^^^^^^^^^^^^
NameError: name 'usercontinue' is not defined
So, instead only catch the exception you expect and allow others to pass, after you fix the issue:
except ValueError:
print('Sorry there was an error with your input')
...
def usercontinue():
# whatever you planned here
pass
Upvotes: 1