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

标签 python

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

的错误
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 语句中乱七八糟。

关于python - 如果出错,是否可以让python打印指定的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6554244/

相关文章:

python - 将字符串与数字进行比较,解码 radio 呼号

python - Ansible:将对象列表传递给 python 脚本

python - 在 Google App Engine (GAE) Datastore 中复制键名和父属性作为属性?

python - 将参数传递给python中的装饰器

java - Python 相当于 Java 的 Set.add()?

python - 如何从无冗余傅立叶变换(例如 PyTorch)到冗余(完整)傅立叶变换?

python - 按日期对对象列表进行排序,其中对象没有名称

python - 有条件生成新列-Pandas

python - 为什么在 Windows 计算机上使用 PyCharm 时无法使用基于 Linux 的 Python 解释器?

python - 字符与 OR 语句的可能组合列表