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?

Joel G Mathew
  • 7,561
  • 15
  • 54
  • 86
  • 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 – DeepSpace Sep 16 '18 at 13:07

1 Answers1

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

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
JPG
  • 82,442
  • 19
  • 127
  • 206
  • 1
    For the sake of completeness I'd add an explanation as to *why* OP's code does not work (see my comment) – DeepSpace Sep 16 '18 at 13:08