-2

In Python, how does one try/except the instantiation of a class?

For example, I'm working on a GitHub script at the moment:

from github3 import login
user = login(username, password)

At first, I thought it would be as easy as:

try:
    user = login(username, password)
except Exception, e:
    print e

However if I force an exception (e.g. provide the wrong arguments), then I don't see any exceptions:

$ python my-script.py -u 1 -p 1; echo $?
name 'pw' is not defined
0

If I try again, but take the try/except out of the mix, I get the exception I expect to see:

$ python my-script.py -u username -p password; echo $?
Traceback (most recent call last):
  File "delete-all-gists.py", line 19, in <module>
    user = login(u, pw)
NameError: name 'pw' is not defined
1 

I can't be the only person who's asked this question, but I'm afraid my SO-search-fu may be failing me...

Update

Indeed, as mentioned in the comments, I appear to have had my eyes closed when asking this...

I think what was throwing me was that github3's login() method was not throwing any sort of exception if the wrong username/password was provided. For example:

from github3 import login
u = 'foo'
p = 'bar'

try:
    user = login(u, p)
except Exception, e:
    print e

Returns:

Nothing. No error, exception or anything.

However, the following does indeed raise an exception, as expected:

from github3 import login
u = 'foo'
p = 'bar'

try:
    user = login(username, p)
except Exception, e:
    print e

Returns:

name 'username' is not defined

Which is, of course, because I purposely provided a non-existent variable as the username parameter to the login() method to force an exception to be raised.

JoeNyland
  • 280
  • 2
  • 22

1 Answers1

3

Remember that any time you run a try/except block it should be because you can REASONABLY HANDLE the exception that occurs. For instance:

username, password = input("Username: "), input("Password: ")
while True:
    try:
        login(username, password)
    except BadPasswordException as e:
        print("Invalid login")
    else:
        # you only get here if there are no exceptions
        break

If you cannot reasonably handle an exception, it's best to log it and let the program gracefully exit.

try:
    foo(some,arguments)
except CthuluHasBeenReleasedException as e:
    logging.fatal("Oh (old) god!")
    sys.exit(1)
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • Yes your answer is correct, but it doesn't answer my question of how to specifically `try`/`catch` the *instantiation* of a class. Your answer basically tells me "If you can't handle an exception, log it and exit". I admit my question is flawed, this answer does not answer the question, IMO. – JoeNyland Aug 02 '14 at 05:25
  • @MasterRoot24 you already know how to catch an exception thrown by instantiating a class, since you did that in your example. What you didn't know was when you should do so. I answered the question you meant to ask, because your question answered the question you asked. – Adam Smith Aug 02 '14 at 06:54
  • My question is specifically about assigning a variable to an instance of a class (`user = login()`) inside a `try`/`except` block, in order to allow methods to be called on that object, for example: `email = user.email()`. Bearing that in mind, how would I use the `User` object returned by the `login()` method in the example given in your answer? – JoeNyland Aug 02 '14 at 07:10
  • @MasterRoot24 so your question isn't about `try/except`, it's about using an instance of a class? I'm very confused.... – Adam Smith Aug 02 '14 at 18:13