如何在Python中编写if-else语句来处理异常/错误?

时间:2017-09-07 07:14:17

标签: python exception error-handling

我正在使用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

如果返回如上所示的错误,我想打印“发生错误。”#39;但是,对于我的if语句,是否有一种方法可以在一般情况下出现回溯错误/错误时进行Python打印?我认为可能有一种更好的方法,而不是设置它像

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

2 个答案:

答案 0 :(得分:1)

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

from twilio.base.exceptions import TwilioRestException

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

答案 1 :(得分:0)

对于这个特定的例外:

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),然后写入文件然后重新加载。这仍然会导致脚本失败,但会有一个日志来查看。