Search code examples
pythonxmpppy

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

Solution

  • 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)