Python Forum

Full Version: problem using custom exception handling in python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am using custom exception in my program along with built in exceptions given by python.
My code is:
class Error(Exception):
      
       pass

class ValueTooSmallError(Error):
      
       pass
class ValueTooLargeError(Error):
       
       pass

# user guesses a number until he/she gets it right
# you need to guess this number
number = 10
while True:
    try:
        i_num = int(input("Enter a number between 1-10: "))
        if i_num < number:
            raise ValueTooSmallError
        elif i_num > number:
            raise ValueTooLargeError
        break
    except ValueTooSmallError:
        print("This value is too small, try again!")
        print()
    except ValueTooLargeError:
        print("This value is too large, try again!")
        print()
print("Congratulations! You guessed it correctly.")
here I want that if user by mistakes enters a string instead of number, it should give ValueError that is the built-in exception in python...how do i use it with custom defined error...I did try but not getting it...Thanx in advance
Whats wrong with ValueError? Why do you need to define custom errors?
Add a except ValueError: to go along with the other exceptions.

Note: if i_num < number: is checking the entered number is less 10, it should be checking for less than 1 based on the input requirements.
Why do you even need exceptions? Why not just put the code from the except blocks back into the conditional blocks that raise the errors in the first place?