Andrii Yurchuk
Andrii Yurchuk

Reputation: 3280

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

Upvotes: 2

Views: 439

Answers (2)

Gareth Latty
Gareth Latty

Reputation: 89097

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)

Upvotes: 3

Marcelo Cantos
Marcelo Cantos

Reputation: 186108

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

Upvotes: 0

Related Questions