0

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?

1
  • 3
    Because type(e) does not return a string. 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). But the correct overall solution would be JPG's answer Commented Sep 16, 2018 at 13:07

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

For the sake of completeness I'd add an explanation as to why OP's code does not work (see my comment)

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.