Skip to main content
 首页 » 编程设计

python之如果出错,是否可以让python打印指定的字符串

2025年05月04日25Renyi-Fan

我的意思是,例如,如果我收到类似

的错误
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 -- Style Guide for Python Code推荐的(任何 Python 程序员的基本读物):

When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause.

另一种(不推荐)方法是:

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

...这是 LBYL 的示例: 三思而后行。这种风格会使您的代码在 if 语句中乱七八糟。