How will you explain that an exception is an object in Python?

PythonServer Side ProgrammingProgramming

Yes in given code ‘err’ is an exception object.

In python everything is an object. And every object has attributes and methods. So exceptions much like lists, functions, tuples etc are also objects. So exceptions too have attributes like other objects. These attributes can be set and accessed as follows. There is the base class exception of which pretty much all other exceptions are subclasses. If e is an exception object, then e.args and e.message are its attributes.

In current Python implementation, exceptions are composed of three parts: the type, the value, and the traceback. The sys module, describes the current exception object in three variables, exc_type, exc_value, and exc_traceback.

The sys.exc_info() function returns a tuple of these three attributes, and the raise statement has a three-argument form accepting these three parts.

Given code gives the following output

(<type 'exceptions.ValueError'>, ValueError('could not convert
string to int: Godzilla!',), <traceback object at 0x0000000002E33748>)

raja
Published on 06-Dec-2017 17:49:29
Advertisements