Question about try, except | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Question about try, except

I’m very confused about what these two things do. If we expect some errors might happen — that’s why we put try/except there at the first place, why don’t we just fix it instead of putting try and except there? Please pardon me if my question is stupid!! I guess my question really is: when and why to use “try, except”? I understand it may be used when we need user input. How about other occasions? Also, except (TypeError): print (“TypeError”) Means “if TypeError happens, print ‘TypeError’”, right? Many thanks!!!’

12th Jun 2019, 7:41 PM
Yang Yang
Yang Yang - avatar
4 Answers
+ 5
There are problems that the coder can't solve. When for example you want to load a file and the user has somehow messed with it and therefore it can't be loaded, how would a coder foresee this? So you use try except in cases where the problem stems from outside the code (where the programmer can't debug). There's another side to it, though: Being 'lazy'. ;-) Pythonists sometimes quote the proverb: 'Better ask for forgiveness than for permission.' For example you could test a user input for all sorts of things to check if it is transformable into a float. You'd have to check if it's only digits, but a point may also be in there. Also, a float can start with zero. Also the exponent may start with a zero, but only if there's exactly one 'e' in the string. In short: You'd have to write quite a bit of code. Instead you can write: try: x = float(input()) except: print('What a pity, no float') So by just trying to convert (and say 'sorry' if it fails) you can save time.
12th Jun 2019, 10:58 PM
HonFu
HonFu - avatar
+ 2
HonFu thank you!!!
13th Jun 2019, 4:03 AM
Yang Yang
Yang Yang - avatar
+ 1
Yes, I am also quite confused of exception handling, when the errors can often be prevented with if statements. Maybe there is still some errors, that can't anyways be prevented, such as Import error, I think there are also some other file handling errors, that are hard to handle with if statements. try: print("Importing gorilla.") import gorilla except ImportError: print("gorilla is not installed!") exit() else: print("Imported gorilla!") If we close file handling off, you can also make typechecking easier within input. try: put = input(": ") int(put) except ValueError: print("Input couldn't be converted to int!")
12th Jun 2019, 9:24 PM
Seb TheS
Seb TheS - avatar
+ 1
Seb TheS thank you!!!
12th Jun 2019, 9:47 PM
Yang Yang
Yang Yang - avatar