try; except:The try: and except: statement allows the programmer to catch an error with out causing the program to crash. The programmer can then modify the logic in code to deal with the error so the program can either continue or close without crashing.
Sample code:This try/except is used with a while loop to guaranteed that an integer is entered by the user. Two other examples are also below. def getInt(): isNotAnInt = True while isNotAnInt: try: myInt = int(input("Enter an integer:")) isNotAnInt = False except: print ("Please Enter an Integer") return myInt
isnotvalid = True while isnotvalid: try: i = int(input("Enter an Integer: ")) isnotvalid = False except: pass print (i)
isnotvalid = True while isnotvalid: try: i = int(input("Enter an Integer: ")) if i>=0 and i<=10: isnotvalid = False else: print ("Enter a number between 0 and 10") except: pass
|
|