开发者

In Python, how to catch the exception you've just raised?

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


Try/except like with all exceptions in python. Here is an example:

def raise_error():
    raise IOError('Error Message')

print('Before Call.')

try:
    raise_error()
except IOError as error:
    print(error)

print('After Call.')

Edit:

To make a more realistic example:

def connect_to_client():
    ...
    if time_since_client_responded > 5000:
        raise ClientTimeoutError(client_name+" timed out.")

...
try:
    connect_to_client("server:22")
except ClientTimeoutError as error:
    print(error)
    sys.exit(1)


Use try: ... except: .... The Python tutorial explains the use of this construct here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜