Can I raise and handle exceptions in the same function -
i raising exception , trying handle exception in snippet. raising exception part , handling exception part done in function. wrong so?
import sys def water_level(lev): if(lev<10): raise exception("invalid level!") print"new level=" # if exception not raised print new level lev=lev+10 print lev try: if(level<10): print"alarming situation has occurred." except exception: sys.stdout.write('\a') sys.stdout.flush() else: os.system('say "liquid level ok"') print"enter level of tank" level=input() water_level(level) #function call
the output not handling exception. can explain me why?
it better raise exception in function , catch it when call function function not , error handling independent. , makes code simpler.
your code never reached except
clause because if water level low raises exception , jumps out of function , if okay reaches else
clause. print
statement in try
clause never reached because same condition 1 raises exception , 1 jumps out.
your code should that...
import sys import os def water_level(level): #just raise exception in function here if level < 10: raise exception("invalid level!") level = level + 10 print("new level=") # if exception not raised print new level print(level) #function call print("enter level of tank") #cast int level=int(input()) try: #call function in here water_level(level) #catch risen exceptions except exception e: sys.stdout.write('\a') sys.stdout.flush() #print exception(verification) print(e) print("alarming situation has occurred.") else: os.system('say "liquid level ok"')
note corrected other flaws
import os
missing- you should cast
input()
number can number comparisions , additions - try avoid catch least specific exception
exception
because catch every other exception too.(thats why addedprint(e)
) -> think custom exceptions
Comments
Post a Comment