Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

Here is code in which an exception is raised.

import sys
try:
    f = int('Godzilla!')
    print f
    raise ValueError
except Exception as err:
       print sys.exc_info()

Is ‘err’ an exception object and what does sys.exc_info() do?


1 Answer
Rajendra Dharmkar

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.