这可能是非常基本但我试图触发Except
如果cointype()
不在字典coin_int
内,则它会直接跳出if
条件不使用Except
即使遇到值错误?
谢谢你的帮助。
try:
coin_type = input("Input your coin: 1p, 2p, 5p etc... ")
if coin_type in coin_int:
print("That value is recognised inside the list of known coin types")
except ValueError:
print("That value of coin is not accepted, restarting...")
答案 0 :(得分:3)
你想提出例外。刚
import * as jwt from 'angular2-jwt/angular2-jwt';
答案 1 :(得分:2)
首先你永远不会达到你的...你不会“尝试”任何会引发ValueError异常的事情......让我先说明一下这个,然后基本上说在这种情况下你不会获益任何使用try / except:
的东西coin_int = ("1p", "2p", "5p")
while True:
coin_type = input("Input your coin: 1p, 2p, 5p etc.: ")
try:
coin_int.index(coin_type)
print("value accepted, continuouing...")
break
except ValueError:
print("That value of coin is not accepted, try again and choose from", coin_int)
但这是等效的,在这种情况下同样有效(如果在性能和可读性方面实际上都不是更好):
coin_int = ("1p", "2p", "5p")
while True:
coin_type = input("Input your coin: 1p, 2p, 5p etc.: ")
if coin_type in coin_int:
print("value accepted, continuouing...")
break
else:
print("That value of coin is not accepted, try again and choose from", coin_int)
如果你真的想要停止程序执行,那么在except:
中执行以下任何操作raise
提出使用默认消息raise ValueError("That value of coin is not accepted, try again and choose from", coin_int)
也可以在else
中用于使用自定义消息引发特定异常答案 2 :(得分:0)
您的程序应如下所示。 (我通过列表而不是字典给出示例)
coin_int = ['1p', '2p', '3p', '4p', '5p']
try:
coin_type = '6p'
if coin_type in coin_int:
print("That value is recognised inside the list of known coin types")
else:
raise ValueError("wrong coin type")
except ValueError as error:
print("That value of coin is not accepted, restarting..." + repr(error))