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


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>)

Updated on: 26-Sep-2019

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements