1.

What is a user defined exception? How is it raised in Python script?

Answer»

Errors detected during execution are called EXCEPTIONS. In Python, all exceptions must be INSTANCES of a class that derives from BaseException. Python library defines many subclasses of BaseException. They are called built-in exceptions. Examples are TypeError, ValueError etc.

When USER code in try: block raises an exception, program control is thrown towards except block of corresponding predefined exception type. However, if the exception is different from built-in ones, user can define a customized exception class. It is called user defined exception.

Following example defines MyException as a user defined exception.

class MyException(Exception):    def __init__(self, num):       self.num=num    def __str__(self):       return "MyException: invalid number"+str(self.num)

Built-in exceptions are raised implicitly by the Python interpreter. However, exceptions of user defined type must be raised explicitly by using raise keyword.

The try: block accepts a number from user and raises MyException if the number is beyond the range 0-100. The except block then processes the exception object as defined.

try:    x=int(input('input any number: '))    if x not in range(0,101):       raise MyException(x)    PRINT ("Number is valid") except MyException as m:    print (m)

Output:

input any number: 55 Number is valid input any number: -10 MyException: invalid number-10


Discussion

No Comment Found