如何捕获内部错误"否则"那"其他"在里面"尝试"。 这是代码:
try:
if appcodex == app:
print "AppCode Confirmed"
if acccodex == acc:
print "Access Code Confirmed"
if cmdcodex == cmd:
print "Command Code Confirmed"
print "All Code Confirmed, Accessing URL..."
else:
print "Command Code not found"
else:
print "Access Code not found"
else:
print "AppCode not found"
except:
print "Error : Code doesn't match..."
当cmdcodex / cmd没有输入时,如何引发"CommandCode not found"
而不是"Error : Code doesn't match..."
。
答案 0 :(得分:3)
您需要创建自己的例外并提升它。它就像创建一个继承自Exception
的类一样简单,然后使用raise
:
>>> class CommandCode(Exception):
... pass
...
>>> raise CommandCode('Not found')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.CommandCode: Not found
答案 1 :(得分:1)
通常你会得到“错误:代码不匹配......”而不是“找不到命令代码”。为什么?答案是基本的:你需要理解handling exceptions in Python的基本概念。
在你的特殊情况下,你必须在试试中包装那段代码..除了块之外,像这样:
try:
if appcodex == app:
print "AppCode Confirmed"
if acccodex == acc:
print "Access Code Confirmed"
try:
if cmdcodex == cmd:
print "Command Code Confirmed"
print "All Code Confirmed, Accessing URL..."
except:
print "Command Code not found"
else:
print "Access Code not found"
else:
print "AppCode not found"
except:
print "Error : Code doesn't match..."
总结一下情况:您可以根据需要嵌套必要的try ... except
块。但是你应该遵循这个PEP