Python - 如果发生异常,则为 "if" 语句

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) 这样的东西可能会抛出异常并可能造成一些伤害。 More information on this can be found here.

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