Difference between except: and except Exception as e:
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.
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
.
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:).