【问题标题】:How do I write if-else statements in Python that work with exceptions/errors?如何在 Python 中编写处理异常/错误的 if-else 语句?
【发布时间】:2017-09-07 07:14:16
【问题描述】:

我正在使用 Twilio 的 API 来返回有关电话号码的信息。部分电话号码无效,返回错误如

Traceback (most recent call last):
  File "test_twilio.py", line 17, in <module>
    number = client.lookups.phone_numbers("(4154) 693-
6078").fetch(type="carrier")
  File "/Users/jawnsano/anaconda/lib/python2.7/site-
packages/twilio/rest/lookups/v1/phone_number.py", line 158, in fetch
    params=params,
  File "/Users/jawnsano/anaconda/lib/python2.7/site-
packages/twilio/base/version.py", line 82, in fetch
    raise self.exception(method, uri, response, 'Unable to fetch 
record')
twilio.base.exceptions.TwilioRestException: 
HTTP Error Your request was:

GET /PhoneNumbers/(4154) 693-6078

Twilio returned the following information:

Unable to fetch record: The requested resource /PhoneNumbers/(4154) 
693-6078 was not found

More information may be available here:

https://www.twilio.com/docs/errors/20404

如果返回如上所示的错误,我想打印 'There is an error.'。但是,对于我的 if 语句,有没有办法让 Python 在一般存在回溯错误/错误时打印它?我认为可能有比设置更好的方法

if returned_value = (super long error message):
    etc...

【问题讨论】:

  • 你能分享你的代码以便更好地理解吗?
  • 不返回错误信息。

标签: python exception error-handling


【解决方案1】:

您使用 try 和 except 来捕获错误。

from twilio.base.exceptions import TwilioRestException

try:
    ... your code
except TwilioRestException:
    print("whatever")

【讨论】:

  • 未来开发者请注意:您需要从twilio.base.exceptions 导入TwilioRestException
【解决方案2】:

对于这个特定的例外:

try:
    the_function_that_raises_the_exception()
except twilio.base.exceptions.TwilioRestException as e:
    print("Oops, exception encountered:\n" + str(e))

请注意,您可能需要先致电import twilio.base.exceptions

对于任何例外:

try:
    the_function_that_raises_the_exception()
except Exception as e:
    print(e)

但在使用第二种方法时要小心 - 这会捕获所有异常,如果处理不当,可能会掩盖更大的问题。除非您知道异常的来源(但如果是这种情况,您知道类型并且只能过滤该类型),有时可以使用这种方法:

try:
    the_function_that_can_raise_numerous_exceptions()
except Exception as e:
    with open("exceptions.txt", "a") as f:
        f.write(e)
    # or even send an email here
    raise

这确保异常被捕获(由except),然后写入文件,然后重新引发。这仍然会导致脚本失败,但需要查看日志。

【讨论】:

  • 您不应该建议捕获所有异常。这几乎不是正确的做法。
  • 是的,正计划扩展答案以警告这种方法 - 刚刚完成!
猜你喜欢
  • 2014-02-15
  • 2022-07-22
  • 2016-04-21
  • 2015-07-03
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
相关资源
最近更新 更多