Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Both the accompanying snippets of code do something very similar. They actually catch each exception and run the code with the except: block 

Code snippet: 1

try:

    #some code that may throw an exception

except:

    #exception handling code

Code snippet: 2

try:

    #some code that may throw an exception

except Exception as e:

    #exception handling code

I need to know the exact difference between both the constructs?

1 Answer

0 votes
by (26.4k points)

In the subsequent you can get to the attributes of the exception object: 

>>> def catch():

...     try:

...         asd()

...     except Exception as e:

...         print e.message, e.args

... 

>>> catch()

global name 'asd' is not defined ("global name 'asd' is not defined",)

However, it doesn't get BaseException or the framework leaving exceptions SystemExit, KeyboardInterrupt, and GeneratorExit: 

>>> def catch():

...     try:

...         raise BaseException()

...     except Exception as e:

...         print e.message, e.args

... 

>>> catch()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

  File "<stdin>", line 3, in catch

BaseException

Where a bare except does:

>>> def catch():

...     try:

...         raise BaseException()

...     except:

...         pass

... 

>>> catch()

>>> 

See the Built-in Exceptions segment of the docs and the Errors and Exceptions part of the instructional exercise for more information.

Are you interested to learn the concepts of Python? Join the python training course fast!

Browse Categories

...