What is this featureless Python exception?
I have a script containing a section similar to this, on Python 2.6:
import sys
list_id='cow'
prev=[0,'cow']
try:
if list_id==prev[1]:
print '{0} is the same as {1}'.format(list_id,prev[1])
sys.exit(0)
except:
print 'exception occurred, exiting with error'
sys.exit(1)
I noticed that though it was printing the 'is the same' line, it also logs the exception!
If you remove the try/except block, the interpreter shows no error. If you catch a specific error like ValueError, the except block is not executed.
import sys
list_id='cow'
prev=[0,'cow']
try:
if list_id==prev[1]:
print '{0} is the same as {1}'.format(list_id,prev[1])
sys.exit(0)
except Exception as k:
print 'exception occurred, exiting with error. Exception is:'
print k.args
sys.exit(1)
The except block is not executed, and the process finishes with return code 0. So, the exception is above Exception in开发者_JAVA技巧 the hierarchy?
import sys
list_id='cow'
prev=[0,'cow']
try:
if list_id==prev[1]:
print '{0} is the same as {1}'.format(list_id,prev[1])
sys.exit(0)
except BaseException as k:
print 'exception occurred, exiting with error. Exception is:'
print k.args
sys.exit(1)
produces
cow is the same as cow exception occurred, exiting with error.
Exception is: (0,)
And the process finishes with exit code 1.
Why is this Except block being executed at all?
sys.exit()
raises SystemExit
, which is what you're seeing.
As to why it doesn't inherit from Exception
:
The exception inherits from
BaseException
instead ofStandardError
orException
so that it is not accidentally caught by code that catchesException
. This allows the exception to properly propagate up and cause the interpreter to exit.
sys.exit()
simply raises SystemExit
. That's how it exits the program. When you catch all exceptions, you also catch SystemExit
.
In addition to other answers: SystemExit does not inherit from Exception, python exception hierarchy: http://docs.python.org/library/exceptions.html
精彩评论