函数失败:引发异常,或返回 FALSE?更好的方法是什么?
我想知道你们如何处理函数失败。您是否引发异常,或者返回错误消息?
eG 我有一个应该连接到外部 com 对象的函数。如果 com 对象尚未通过其他程序启动,则无法建立连接。通知主程序的首选 python 方式是什么?我应该提出带有详细错误消息的异常,还是应该简单地返回错误消息?
谢谢!
I was wondering how you guys handle functions fails. Do you raise an exception, or do you return an error message?
e.G. I have a function that is supposed to connect to an external com-object. If the com-object has not been initiated through another program, the connection cannot be established. What would be the preferred python way of notifying the main program? Should I raise an exception with the detailed error message, or should I simple return the error message?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
python 在这里绝对倾向于异常。我一直发现这篇文章是一个很好的解释。
python absolutely comes down on the side of exceptions here. i have always found this article to be a great explanation.
抛出异常,这就是它们的用途。
它们允许使用您的代码来管理错误,传回字符串提供了太多错误处理的机会。
考虑一下您通常返回字符串或可迭代的情况,检查错误消息可能会导致问题,并且可能无法始终捕获它们,这也不是很Pythonic。
Throw an exception, this is what they are there for.
They allow the things using your code to manage the error, passing back strings provides too much opportunity for mishandling.
Consider the case you return a string or an iterable normally, checking for an error message could cause problems, and may not catch them all the time, it's also not very Pythonic.