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.