+ 2
Python Core - 42.2 Practice (Exception Handling)
Hey guys, Can someone explain to me what's wrong with this code: pin = int(input()) try: print("PIN code is created") except ValueError: print("Please enter a number") The error is defined in the exception, however it doesn't seem to be catching it, despite showing that the error is indeed occurring, as shown below. " Traceback (most recent call last): File "/usercode/file0.py", line 1, in <module> pin = int(input()) ValueError: invalid literal for int() with base 10: 'hh88' " As far as I can tell that should be all that's required, but I'm a noob and am probably missing something pretty obvious. Thanks!
6 odpowiedzi
+ 7
try:
pin = int(input())
# PIN created
except ValueError:
# Please enter a number
The exception is uncaught because the conversion to int is performed outside the try...except block.
+ 4
As Ipang pointed out the conversion has to be placed in the try block. As a rule everything that might throw an error should be put in a try block.
+ 3
Well now, that was a bit of a dirty trick, they defined the pin variable outside of the try.. except block in the first place:
pin = input()
try:
#your code goes here
except ValueError:
#and here
Lesson learned, don't trust the default code haha. Thank you!
+ 3
They put the input there, but not the conversion. But yes, it's a bit unfortunate since most people convert the input immediately.
+ 1
pin = input()
try:
int(pin)
print("PIN code is created")
except :
print("please enter the number")
Guys real code is this👆
0
I had a similar problem, thank you guys for sharing your knowledge with us <3