Forums

Try/Except issue with exiting program on error

Hi, I am new (actually very new) to using Python and I am trying to figure out how to stop code from running and printing error message if there is an error using try/except. I thought I could add quit() or sys.exit(1) , but both of those are not recognized and come back with an error code of their own. Any help would be greatly appreciated. Here is the code:

def computepay(h,r):
return(h*r)

hrs = input("Enter Hours:")
rate = input('Enter Rate:')
try:
       h = float(hrs)
       r = float(rate)
except:
        print('Error, please enter numeric value')
       quit()
p = computepay(h,r)
print("Pay",p)

What error message do you get if you use sys.exit(1)? That's certainly the normal way to exit a program with an error code.

(One possibility -- when you were using sys.exit, did you have a line saying import sys near the top of your code?)

Hi and thank you for your response,

Here is the error message I get when I enter a string value for hours: (this occurred with import sys at top of code and sys.exit(1) at the end of the except line of code...

Error, please enter numeric value
Traceback (most recent call last):
  File "/home/rockmono/PY4E 4_6.py", line 11, in <module>
    h = float(hrs)
ValueError: could not convert string to float: 'ten'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/home/rockmono/PY4E 4_6.py", line 15, in <module>
    sys.exit(1)

How are you running the code? If it's using the ">>>" button in the editor, that might be the problem. When you run code that way, it tries to run it in an interactive session, which will keep running when your program has exited. This means that errors are reported differently to how they would if you just ran it as a simple script.

To run it as a simple script, just start a Bash console from the "Consoles" page, then run the command

python3.6 "PY4E 4_6.py"

I tried running program from Bash console and still received error when inputting a string (to activate except code). Must be something wrong with my code and the way I worded the if/except code. I will rework code and see it I still get the same error message. I do appreciate your time and assistance. Learning Python has been a humbling experience for me and I have just begun. I hope it will all click for me at some point.