Reputation: 8061
I was trying to catch a specific exception:
username = 'myuser'
try:
user = User.objects.get(username=username)
print(user)
except Exception as e:
if type(e)=='django.contrib.auth.models.User.DoesNotExist':
print('No such user')
print (type(e))
But instead of going into the if loop, I am getting:
<class 'django.contrib.auth.models.User.DoesNotExist'>
Why is this happening? How can I catch a specific exception?
Upvotes: 0
Views: 69
Reputation: 88429
type(e)
does not return a string. Note that
(<class 'django.contrib.auth.models.User.DoesNotExist'> !=
'django.contrib.auth.models.User.DoesNotExist')
The if
condition should be if type(e) == django.contrib.auth.models.User.DoesNotExist
or better, if isinstance(e, django.contrib.auth.models.User.DoesNotExist)
However, the correct solution is to use multiple except
clauses
username = 'myuser'
try:
user = User.objects.get(username=username)
print(user)
except User.DoesNotExist:
# do something
print('No such user')
except SomeOtherException:
# do a different thing
except Foo:
# do bar
Note that you can also combine handling of different exception types to the same except
clause:
try:
# some bad code
except (User.DoesnotExist, SomeOtherException):
# error handling code
Reference
1. Python: One Try Multiple Except
Upvotes: 4