Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to implement user defined exception in Python?

I have a user defined or custom exception as follows

class CustomException(Exception):
   def __init__(self, arg):
      self.args = arg

How do I raise and implement this CustomException?


1 Answer
Manogna

We create user-defined or custom exceptions by creating a new exception class in Python. The idea is to derive the custom exception class from the exception class. Most built-in exceptions use the same idea to enforce their exceptions.

In the given code, you have created a user-defined exception class, the “CustomException“. It is using the Exception class as the parent. Hence, the new user-defined exception class will raise exceptions as any other exception class does i.e. by calling the “raise” statement with an optional error message.

Let’s take an example.

In this example, we show how to raise a user-defined exception and catch errors in a program. Also, in the sample code, we ask the user to enter an alphabet again and again until he enters the stored alphabet only.

For help, the program provides a hint to the user so that he can figure out the correct alphabet.

#Python user-defined exceptions
class CustomException(Exception):
"""Base class for other exceptions"""
pass
class PrecedingLetterError(CustomException):
"""Raised when the entered alphabet is smaller than the actual one"""
pass
class SucceedingLetterError(CustomException):
"""Raised when the entered alphabet is larger than the actual one"""
pass
# we need to guess this alphabet till we get it right
alphabet = 'k'
while True:
try:
foo = raw_input ( "Enter an alphabet: " )
if foo < alphabet:
raise PrecedingLetterError
elif foo > alphabet:
raise SucceedingLetterError
break
except PrecedingLetterError:
print("The entered alphabet is preceding one, try again!")
print('')
except SucceedingLetterError:
print("The entered alphabet is succeeding one, try again!")
print('')
print("Congratulations! You guessed it correctly.")

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.