+ 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!

31st Aug 2021, 12:33 AM
Boeo2958
6 Antworten
+ 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.
31st Aug 2021, 12:37 AM
Ipang
+ 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.
31st Aug 2021, 12:43 AM
Simon Sauter
Simon Sauter - avatar
+ 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!
31st Aug 2021, 12:42 AM
Boeo2958
+ 3
They put the input there, but not the conversion. But yes, it's a bit unfortunate since most people convert the input immediately.
31st Aug 2021, 12:48 AM
Simon Sauter
Simon Sauter - avatar
+ 1
pin = input() try: int(pin) print("PIN code is created") except : print("please enter the number") Guys real code is this👆
1st Dec 2022, 2:51 AM
Shamanth Kumar K
Shamanth Kumar K - avatar
0
I had a similar problem, thank you guys for sharing your knowledge with us <3
21st Jun 2022, 8:09 PM
Alexander Repollo
Alexander Repollo - avatar