Python - 一个" if"声明是否发生异常

时间:2015-03-15 19:28:43

标签: python exception if-statement

我想在异常消失后发生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()

3 个答案:

答案 0 :(得分:6)

您不应该需要条件,因为如果您在except块中,则表示发生了异常

答案 1 :(得分:1)

目前还不清楚你想在这里实现什么目标。如果发生异常,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)这样的东西可能会抛出异常并可能造成一些伤害。 More information on this can be found here.

答案 2 :(得分:-1)

我在这里找到了这个: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()