Python raise和raise fromPython 之间的区别是什么?
try:
raise ValueError
except Exception as e:
raise IndexError
Run Code Online (Sandbox Code Playgroud)
产量
Traceback (most recent call last):
File "tmp.py", line 2, in <module>
raise ValueError
ValueError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "tmp.py", line 4, in <module>
raise IndexError
IndexError
Run Code Online (Sandbox Code Playgroud)
和
try:
raise ValueError
except Exception as e:
raise IndexError from e
Run Code Online (Sandbox Code Playgroud)
产量
Traceback (most recent call last):
File "tmp.py", line 2, in <module>
raise ValueError …Run Code Online (Sandbox Code Playgroud) 我有一个小的 python 代码,我在其中使用了异常处理。
def handler(event):
try:
client = boto3.client('dynamodb')
response = client.scan(TableName=os.environ["datapipeline_table"])
return response
except Exception as error:
logging.exception("GetPipelinesError: %s",json.dumps(error))
raise GetPipelinesError(json.dumps({"httpStatus": 400, "message": "Unable to fetch Pipelines"}))
class GetPipelinesError(Exception):
pass
Run Code Online (Sandbox Code Playgroud)
pylint 警告给了我“考虑使用 'from' 关键字明确重新提高”。我很少看到其他帖子,他们使用 from 并引发错误。我做了这样的修改
except Exception as GetPipelinesError:
logging.exception("GetPipelinesError: %s",json.dumps(GetPipelinesError))
raise json.dumps({"httpStatus": 400, "message": "Unable to fetch Pipelines"}) from GetPipelinesError
Run Code Online (Sandbox Code Playgroud)
这是正确的做法吗?