Quantcast
Channel: Catch specific errors in python - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Answer by JPG for Catch specific errors in python

$
0
0

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 thingexcept Foo:    # do bar

Note that you can also combine handling of different exception types to the same except clause:

try:    # some bad codeexcept (User.DoesnotExist, SomeOtherException):    # error handling code


Reference
1. Python: One Try Multiple Except


Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>