在Python中,如何捕获刚刚引发的异常?
我有这段代码:
jabberid = xmpp.protocol.JID(jid = jid)
self.client = xmpp.Client(server = jabberid.getDomain(),
debug = [])
if not self.client.connect():
raise IOError('Cannot connect to Jabber server')
else:
if not self.client.auth(user = jabberid.getNode(),
password = password,
resource = jabberid.getResource()):
raise IOError('Cannot authenticate on Jabber server')
它使用 xmpppy。由于 xmpppy 在无法连接或身份验证时不会抛出任何异常,因此我需要自己抛出它们。问题是,如何捕获抛出的异常以仅输出错误消息,而不输出完整的回溯,并保持代码运行?
编辑
这样的构造合适吗?
def raise_error():
raise IOError('Error ...')
if not self.client.connect():
try:
self.raise_error()
except IOError, error:
print error
I've got this piece of code:
jabberid = xmpp.protocol.JID(jid = jid)
self.client = xmpp.Client(server = jabberid.getDomain(),
debug = [])
if not self.client.connect():
raise IOError('Cannot connect to Jabber server')
else:
if not self.client.auth(user = jabberid.getNode(),
password = password,
resource = jabberid.getResource()):
raise IOError('Cannot authenticate on Jabber server')
It's using xmpppy. Since xmpppy does not throw any exceptions if it could not connect or authenticate, I need to throw them myself. The question is, how do I catch those exceptions I throw to output only the error message, but not the full traceback, and keep the code running despite them?
EDIT
Is this construction appropriate?
def raise_error():
raise IOError('Error ...')
if not self.client.connect():
try:
self.raise_error()
except IOError, error:
print error
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Try/ except 就像 python 中的所有异常一样。这是一个例子:
编辑:
制作一个更现实的例子:
Try/except like with all exceptions in python. Here is an example:
Edit:
To make a more realistic example:
使用
尝试:...除了:...
。 Python 教程在此处解释了此构造的用法。Use
try: ... except: ...
. The Python tutorial explains the use of this construct here.