我如何在Python中编写IF-ELSE语句,以与异常/错误一起使用



我正在与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

如果返回上面显示的错误,我想打印"有错误"。但是,对于我的if语句,是否有一种方法可以使python打印在一般情况下发生追溯错误/错误时?我认为可能有一种比设置像

的更好的方法
if returned_value = (super long error message):
    etc...

您使用的尝试和除了捕获错误。

from twilio.base.exceptions import TwilioRestException
try:
    ... your code
except TwilioRestException:
    print("whatever")

对于此特定异常:

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),然后写入文件,然后将其重新编写。这仍然会导致脚本失败,但将有一个登录。

最新更新