簡體   English   中英

如果出現錯誤,是否可以讓 python 打印指定的字符串?

[英]Is it possible to make python print a specified string if it get an error?

我的意思是,例如,如果我收到類似的錯誤

Traceback (most recent call last):
  File "score_keeper-test.py", line 106, in <module>
    app = program()
  File "score_keeper-test.py", line 37, in __init__
    self.label1.set_text(team1_name)
TypeError: Gtk.Label.set_text() argument 1 must be string, not None

有沒有辦法讓 python 打印類似“您必須在兩個框中輸入名稱”而不是上面的錯誤?

Pythonic 的成語是EAFP :請求寬恕比請求許可更容易。 在這種情況下:

try:
    self.label1.set_text(team1_name)
except TypeError:
    print "You MUST enter a name in the TWO boxes"

請注意我是如何明確捕獲TypeError的。 這是PEP 8 推薦的——Python 代碼的樣式指南(任何 Python 程序員的基本讀物):

捕獲異常時,盡可能提及特定的異常,而不是使用裸的except:子句。

另一種(不推薦)方法是:

if team1_name:
    self.label1.set_text(team1_name)
else:
    print "You MUST enter a name in the TWO boxes"

...這是LBYL的一個例子:在你跳躍之前先看看。 這種風格會讓你的代碼在if語句中亂七八糟。

if value:
   #Do stuff
else:
   print "You MUST enter a name in the TWO boxes"

現在,在這里,如果value None ,它將打印字符串 - “您必須在兩個框中輸入名稱”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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