2

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
Andrii Yurchuk
  • 3,090
  • 6
  • 29
  • 40

2 Answers2

3

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)
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
  • 1
    It's better to create user-defined exceptions as an [Exception class](http://docs.python.org/tutorial/errors.html). – Ben Sep 24 '11 at 10:40
  • This is true, I was simply emulating the question for this answer. – Gareth Latty Sep 24 '11 at 10:42
  • @Lattyware Please look at the EDIT of the question. Is this what you mean? – Andrii Yurchuk Sep 24 '11 at 10:59
  • @AndriyYurchuk No, My example was just that, an example. You should simply do 'raise WhateverError('Message')' whenever you want to raise an error. Then when you write the code that uses that function (say the function that connects in your example), then you wrap that code in a try/except block as I showed. – Gareth Latty Sep 30 '11 at 22:44
0

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

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365