【问题标题】:Python - An "if" statement if an exception occursPython - 如果发生异常,则使用“if”语句
【发布时间】:2015-05-17 21:07:01
【问题描述】:

我希望在异常发生后执行 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 块中,则异常已经发生。这不是充分条件吗?

标签: python exception if-statement


【解决方案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()

【讨论】:

    【解决方案2】:

    目前尚不清楚您要在这里实现什么。 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.

    【讨论】:

      【解决方案3】:

      您不需要条件,因为如果您在 except 块中,则意味着发生了异常

      【讨论】:

        猜你喜欢
        • 2022-07-22
        • 1970-01-01
        • 2017-03-04
        • 2014-02-15
        • 2019-03-03
        • 2014-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多