0
what is try:? where can it be used?
can anybody define "try:" what is its usage and applications?
4 odpowiedzi
+ 2
try is used for error / exception handling. not sure if you're familiar with java and other languages, but same idea. I forget exact syntax (you can Google it), but something like:
try:
x = int(input("give me an integer, bro:"))
break
except ValueError:
print("that's not a valid integer!")
this is a simple case of error handling where you expect a certain type to be input (int in our case), and get something else (ex. user inputs "seven", which is a string).
if valid input is given in above example, say 7, then the except part is skipped and the code continues.
there are tons of applications. exploits are usually made from taking advantage of bad, or no, error handling.
+ 2
correct..there is another clause for try called finally which is executed no matter what. a little more complex to explain, but see below:
try:
x = input("please press a key and I'll reward you!")
raise KeyboardInterrupt
finally:
print("Thank you for pushing my buttons!")
+ 2
It is recommended to use that every time you can. You never know if exception will rise and it good for handling your code.
+ 1
So basically we use try: only when we use exception. i got this question because in exception module it was not explained and suddenly they started using it. Thanks for your explanation. i will learn more it from other sources.