Raise Keyword In Python

The raise key word is used to programmatically generate an exception in a Python Program. The exception handling mechanism of Python is provided through the keywords: try, except, finally and raise. 

Both the forms of raise given here do the same thing - they raise an exception.

raise <An instance of the exception>

or

raise <Name of the exception class>

Any code potential of generating an exception can be wrapped inside a try block and a set of except blocks one of which handles the exception.  

Once an exception is generated Python searches for a matching except handler. If one is not found in the current scope, the search is continued in enclosing scopes till an exception handler is found. The exception is handled by the found exception handler. If the exception handler is not found the program prints the  traceback and exits. 

 

Example:

class NameException(Exception):
    pass

def procName(nameVal):
    if nameVal.isalnum() is False:
        raise NameException

procName("Rutherford$");

 

Output:

Traceback (most recent call last):

  File "raise_ex.py", line 8, in <module>

    procName("Rutherford$");

  File "raise_ex.py", line 6, in procName

    raise NameException

__main__.NameException

 

Example:

class NameException(Exception):

    def __init__(self, message):

        self.message = message

 

def procName(nameVal):

    if nameVal.isalnum() is False:

        raise NameException("Exception:Special characters not allowed in name")

try:

    procName("Rutherford$");

except NameException as NameEx:

    print(NameEx.message)   

except Exception as Ex:

    print(Ex)    

Output:

Exception:Special characters not allowed in name

 


Copyright 2023 © pythontic.com