请检查以下代码,
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)
我给eval raw_input
函数添加了一个字符串。
$> python test.py
Enter seq number: "12"
Sequence number not in range [0001-9999]
!!! Sequence number not in range [0001-9999]
为什么即使在收到exit
电话后它也没有退出?
答案 0 :(得分:8)
sys.exit
只会引发异常(SystemExit
),然后会被捕获。作为示范:
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
答案 1 :(得分:3)
sys.exit
引发您的未命名异常处理程序捕获的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)
答案 2 :(得分:1)
这是一个很好的例子,为什么你永远不应该使用裸露的除外。无效的数字是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)
输出:
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
注意eval
也不赞成,因为它会执行用户输入的任何内容,例如import shutil; shutil.rmtree('/')
。