簡體   English   中英

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)之類的內容可能會引發異常,並可能造成某些危害。 有關更多信息,請參見此處。

我在這里找到了這個: 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM