Rolling Your Own Exceptions in python

Rolling Your Own Exceptions in python

Rolling Your Own Exceptions in python

You can roll your own exceptions by creating a new exception class, which you should inherit from one of the system exception classes. Alternatively, for backward compatibility, you can also create a string-based exception, as in the following example:

CustonError = 'Error"

raise CustomError


Note that exceptions match against values, so raising a string exception but checking against the object still works:

customError = 'Error'

def test( ):

       raise 'Error"

try:

   test()

except CustomError: 

             print "Error!"

However, it’s bad practice to rely on this, so you should instead raise one of the predefined error strings. To create class-based exceptions, create a new class, including any initialization information. You can then raise the exception, with any additional information, for parsing by an exception handler. The additional data collected by an except statement is extracted from the args attribute of an exception object, as in the following example:

class MyNameException (Exception): 

      def_init_(self, name, msg): 

            self.args = (name, msg)

try:

raise MyNameException( 'Marvin', 'Not my real name') 

except MyNameException, (name, msg): print 'Sorry, but', name, 'is'.msg


You’ll be seeing some other examples of object/class-based exceptions throughout this book.

Note:- Although Python doesn’t currently enforce it, you should base your exception classes on one of the built-in exception classes. This will enable you and programmers using your code and exceptions to trace problems using one of the generic, higher-level classes as a catch-all, rather than needing to explicitly specify your exception class. String-based exceptions are outside of this hierarchy and should be avoided.

Previous articlein-built functions in python(full details)
Next articlePython fundamentals (python fundamentals free course)

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here