2

In Python 3.x, what is the correct syntax to handle exceptions that have parameters. I'm specifically trying to handle WriteError documented on this page.

I'm writing the code to handle it as:

   except pymongo.errors.WriteError(err, code, dtls):
       logging.error("DB Write Error. err={}; code={}; dtls={}".format(err, code, dtls))

This is not working.

I even had a look at the Erros and Exceptions documentation. But could not find it there.

Can you please tell me the correct way to handle these sort of exceptions?

2 Answers 2

1

You catch the error first, then examine its attributes (reraising the exception if it isn't one you want to handle). There is no pattern matching on the contents of the exception.

except pymongo.errors.WriteError as exc:
    logging.error("DB WriteError. err={}; code={}; dtls={}".format(exc.err, exc.code, exc.dtls))
Sign up to request clarification or add additional context in comments.

1 Comment

How silly of me. You are right. I was trying to pattern match and didn't think about assigning it to a variable. Thanks.
1

The except block just needs the exception's type. Within the block you could, of course, use its attributes if you wish:

except pymongo.errors.WriteError as e:
   logging.error("DB Write Error. err={}; code={}; dtls={}".format(e.err, e.code, e.dtls))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.