i

Python Programming

Raising Exceptions

We can raise exceptions in several ways by using raise statement. The general syntax for raise statement is follows.

Syntax

raise [Exception [,args [,traceback]]

Exception is type of exception and argument is a value for the exception argument. The argument is optional if not supplied exception argument None.

Final argument, traceback, also optional, and if present, is traceback object used for  exception.

Example

An exception can be string, class or object. Most of the exceptions that Python core raises are classes, with argument that is an instance of class.

def functionname(level):

   if level <2:

      raise "Invalid level!"

Note: To catch exception, an "except" clause refer to the same exception thrown either class object or simple string.

try:

   Business Logic should come here...

except "Invalid levell!":

   Exception handling should be here...

else

   Rest of the code should be here...