258

Both the following snippets of code do the same thing. They catch every exception and execute the code in the except: block

Snippet 1 -

try:
    #some code that may throw an exception
except:
    #exception handling code

Snippet 2 -

try:
    #some code that may throw an exception
except Exception as e:
    #exception handling code

What is exactly the difference in both the constructs?

petezurich
  • 9,280
  • 9
  • 43
  • 57
narendranathjoshi
  • 2,876
  • 2
  • 19
  • 19
  • 11
    @user2725093 that's not the same question. The one you linked to asks what's the difference between `except Exception, e:` and `except Exception as e:`. This question asks what the difference is between `except:` and `except Exception as e:`. – Dennis Nov 09 '13 at 22:39

5 Answers5

281

In the second you can access 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",)

But it doesn't catch BaseException or the system-exiting 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

Which a bare except does:

>>> def catch():
...     try:
...         raise BaseException()
...     except:
...         pass
... 
>>> catch()
>>> 

See the Built-in Exceptions section of the docs and the Errors and Exceptions section of the tutorial for more info.

myildirim
  • 2,248
  • 2
  • 19
  • 25
agf
  • 171,228
  • 44
  • 289
  • 238
  • 38
    Well, there's no magic here. ``Exception`` is derived from ``BaseException``, that's why ``except Exception`` does not catch ``BaseException``. If you write ``except BaseException``, it'll be caught too. Bare ``except`` just catches everything. – fjarri Sep 27 '13 at 00:55
  • 3
    I should point out that a bare `except` must be last in a series of `except` blocks, while you won't get an error if you put `except Exception` before other `except` blocks: they'll just get ignored silently (if they handle `Exception` subclasses). Something to watch out for. – Vanessa Phipps Jul 22 '14 at 20:53
  • @MatthewPhipps That's sort of the point, isn't it? like case statements or if-else blocks, execution jumps to the first condition that matches... – Basic Sep 04 '14 at 15:14
  • 1
    @Basic Just pointing out another difference between bare `except` and `except Exception`. "Something to watch out for" looks a little weird now, but at the time I expected Python to pick the most specific `except` block, regardless of where it was, and was a little disappointed to find out otherwise. – Vanessa Phipps Sep 05 '14 at 15:37
  • It is also worth noting that the second form should only be used if you do not care about what the exception was or wish to handle it in a meaningful way. – Josh J Apr 26 '19 at 20:47
  • @JoshJ Can you clarify what you mean? The "second form" in the original question is the one that captures the exception to an object, so not sure why in that one would would be if you didn't care what the exception is. – agf Apr 27 '19 at 21:05
  • @agf I meant the second form in this answer since the answer lists them opposite of the original question. – Josh J Apr 28 '19 at 23:51
  • Note: this is for python 2 – Anonyme2000 Nov 09 '20 at 08:16
91
except:

accepts all exceptions, whereas

except Exception as e:

only accepts exceptions that you're meant to catch.

Here's an example of one that you're not meant to catch:

>>> try:
...     input()
... except:
...     pass
... 
>>> try:
...     input()
... except Exception as e:
...     pass
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyboardInterrupt

The first one silenced the KeyboardInterrupt!

Here's a quick list:

issubclass(BaseException, BaseException)
#>>> True
issubclass(BaseException, Exception)
#>>> False


issubclass(KeyboardInterrupt, BaseException)
#>>> True
issubclass(KeyboardInterrupt, Exception)
#>>> False


issubclass(SystemExit, BaseException)
#>>> True
issubclass(SystemExit, Exception)
#>>> False

If you want to catch any of those, it's best to do

except BaseException:

to point out that you know what you're doing.


All exceptions stem from BaseException, and those you're meant to catch day-to-day (those that'll be thrown for the programmer) inherit too from Exception.

Veedrac
  • 58,273
  • 15
  • 112
  • 169
  • `except(Exception)` never catches `KeyboardInterrupt` errors. `as e` doesn't have anything to do with it. – pandita Sep 24 '13 at 13:25
  • 3
    I never said that it did. I haven't once mentioned the `as e`, because I assumed it's obvious what it does. – Veedrac Sep 24 '13 at 13:28
  • 4
    Is there a case where a person would catch BaseException AND know what they are doing? – Davos Apr 23 '18 at 12:27
  • 2
    @Davos Yeah, you might prefer it when doing transient logging, or if you're offering a console to the user that you don't want exceptions like `SystemExit` or `KeyboardInterrupt` to escape from. Not a common case, but it does happen. – Veedrac Apr 23 '18 at 14:04
20

There are differences with some exceptions, e.g. KeyboardInterrupt.

Reading PEP8:

A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).

Diego Herranz
  • 2,857
  • 2
  • 19
  • 34
8

Another way to look at this. Check out the details of the exception:

In [49]: try: 
    ...:     open('file.DNE.txt') 
    ...: except Exception as  e: 
    ...:     print(dir(e)) 
    ...:                                                                                                                                    
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'with_traceback']

There are lots of "things" to access using the 'as e' syntax.

This code was solely meant to show the details of this instance.

jouell
  • 3,288
  • 1
  • 18
  • 15
4

Using the second snippet gives you a variable (named based upon the as clause, in your example e) in the except block scope with the exception object bound to it so you can use the information in the exception (type, message, stack trace, etc) to handle the exception in a more specially tailored manor.

ARNON
  • 1,097
  • 1
  • 15
  • 33
Silas Ray
  • 25,682
  • 5
  • 48
  • 63