Python Forum
problem using custom exception handling in python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: problem using custom exception handling in python (/thread-19531.html)



problem using custom exception handling in python - srm - Jul-03-2019

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


RE: problem using custom exception handling in python - perfringo - Jul-03-2019

Whats wrong with ValueError? Why do you need to define custom errors?


RE: problem using custom exception handling in python - Yoriz - Jul-03-2019

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.


RE: problem using custom exception handling in python - ichabod801 - Jul-03-2019

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?