Search code examples
custom-exceptions

Can I raise and handle exceptions in the same function


I am raising an exception and trying to handle the exception in snippet. The raising exception part and handling exception part are done in a function. Is it wrong to do so?

import sys

def water_level(lev):
    if(lev<10):
        raise Exception("Invalid Level!") 

    print"New level=" # If exception not raised then 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 the level of tank"
level=input()
water_level(level) #function call 

The output is not handling exception. Can someone explain me why?


Solution

  • It is better to just raise the exception in the function and then catch it it when you call the function so your function does not do too much and your error handling is independent. And it makes your code simpler.

    Your code never reached your except clause because if the water level is too low it raises an exception and jumps out of the function and if it was okay it just reaches the else clause. The print statement in your try clause is also never reached because it is the same condition than the one that raises your exception and that one jumps out.

    Your code should be something like 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 then print new level
      print(level)
    
    #function call
    print("Enter the level of tank")
    
    #cast to int
    level=int(input())
    
    try:
        #call function in here
        water_level(level)
    
    #catch risen exceptions
    except Exception as 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 that i corrected some other flaws

    • import os was missing
    • you should cast your input() to a number so you can do number comparisions and additions
    • try to avoid to catch the least specific Exception Exception because you will catch every other Exception too.(thats why i added the print(e)) -> think about custom exceptions