0
importance of the code try and except in python
why do these 2 codes important? can't i just create a program that have no try/except? and how will you know when to put these codes in your program?
2 Answers
+ 4
sure it works without.
There are other ways
and it is a question of quality.
let it crash if you wsnt.
+ 3
Depends. If there is possibility of crashing, use try and except. Like, if the user inputs a string when you want an integer, let's face it: it's going to crash;
a = int(input("Enter a number: "))
print(a+10)
#Input: 10 Output: 20
#Input: Hi Output: Error
But if you are smart, you would have prepared for that;
try:
a = int(input("Enter a number: "))
print(a+10)
except:
print("Please try again.")
#Input: 10 Output: 20
#Input: Hi Output: Please try again.
Thus the system would not crash. Knowing this may be key to the user-friendliness of your program, so I'd take more notice of these.
Hope this helped! đ