[英]Python: why except is called even after exit
Please check the below code, 请检查以下代码,
import sys
try:
seq=eval(raw_input("Enter seq number: "))
if seq <= 0 or seq >= 9999:
print "Sequence number not in range [0001-9999]"
sys.exit(1)
except:
print "!!! Sequence number not in range [0001-9999]"
sys.exit(1)
I gave a string to eval raw_input
function. 我给
eval raw_input
函数提供了一个字符串。
$> python test.py
Enter seq number: "12"
Sequence number not in range [0001-9999]
!!! Sequence number not in range [0001-9999]
Why is it not exiting even after receiving exit
call? 为什么即使接到
exit
呼叫后仍不退出?
sys.exit
just raises an exception ( SystemExit
), which is then caught. sys.exit
只会引发一个异常( SystemExit
),然后将其捕获。 As a demonstration: 作为演示:
import sys
import traceback
try:
sys.exit(1)
except:
print "This threw the following exception:"
traceback.print_exc()
# This threw the following exception:
# Traceback (most recent call last):
# File "test.py", line 5, in <module>
# sys.exit(1)
# SystemExit: 1
sys.exit
raises the SystemExit
exception which is caught by your unnamed exception handler sys.exit
引发SystemExit
异常,该异常由未命名的异常处理程序捕获
Note, it is usually not a good idea to have a generic exception handler as its evident here. 注意,在此处具有通用异常处理程序通常不是一个好主意。
So as to avoid catching the SystemExit
with your generic exception handler, add another exception handler to handler your SystemExit
为了避免使用您的通用异常处理程序捕获
SystemExit
,请添加另一个异常处理程序以处理您的SystemExit
>>> try:
seq=eval(raw_input("Enter seq number: "))
if seq <= 0 or seq >= 9999:
print "Sequence number not in range [0001-9999]"
sys.exit(1)
except SystemExit:
pass
except Exception:
print "!!! Sequence number not in range [0001-9999]"
sys.exit(1)
This is an excellent case why you should never use a bare except. 这是一个绝妙的案例,为什么您不应该使用裸机。 Invalid numbers are ValueErrors, so:
无效的数字是ValueErrors,因此:
import sys
try:
seq = int(raw_input("Enter seq number: "))
if seq <= 0 or seq >= 9999:
raise ValueError('sequence number not in range [0001-9999]')
except ValueError as e:
print e
sys.exit(1)
Output: 输出:
C:\>test
Enter seq number: 10000
sequence number not in range [0001-9999]
C:\>test
Enter seq number: abc
invalid literal for int() with base 10: 'abc'
C:\>test
Enter seq number: 5
Note eval
is also frowned upon, because it will execute whatever the user types, such as import shutil; shutil.rmtree('/')
注意,
eval
也不适用,因为它将执行任何用户类型的操作,例如import shutil; shutil.rmtree('/')
import shutil; shutil.rmtree('/')
. import shutil; shutil.rmtree('/')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.