[英]Python - An “if” statement if an exception occurs
我希望一旦异常消失,就会发生if语句。 它的功能是什么,或者甚至有可能?
这就是我想要得到的
try:
save_this_number_file(s)
except:
print("could not find file. Don't forget to add *.txt* to the end of file name.")
if (except):
again = input("Would you like to try again? (y/n) ")
if (again != 'y'):
sys.exit()
您不需要条件,因为如果您位于except
块中,则意味着发生了异常
目前尚不清楚您要在这里实现什么。 凡是在except
例行如果出现异常, 只运行。 因此,您可以使用:
try:
save_this_number_file(s)
except:
print("could not find file. Don't forget to add *.txt* to the end of file name.")
again = input("Would you like to try again? (y/n) ")
if (again != 'y'):
sys.exit()
如果要在发生其他情况后运行代码,则只需将布尔值设置为发生异常即可。
顺便说一句,您应该尝试说出要捕获的异常。 如果您不这样做,则诸如KeyboardInterrupt(^ C)之类的内容可能会引发异常,并可能造成某些危害。 有关更多信息,请参见此处。
我在这里找到了这个: http : //www.tutorialspoint.com/python/python_exceptions.htm
try:
You do your operations here;
except:
If there is any exception, then execute this block.
else:
If there is no exception then execute this block.
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.