我正在尝试捕获特定的异常:
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))
但是我没有进入if循环,而是得到:
<class 'django.contrib.auth.models.User.DoesNotExist'>
为什么会这样?如何捕获特定的异常?
答案 0 :(得分:5)
type(e)
不返回字符串。请注意
(<class 'django.contrib.auth.models.User.DoesNotExist'> !=
'django.contrib.auth.models.User.DoesNotExist')
if
条件应为if type(e) == django.contrib.auth.models.User.DoesNotExist
或更高,if isinstance(e, django.contrib.auth.models.User.DoesNotExist)
但是,正确的解决方案是使用多个 except
子句
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
请注意,您还可以将对不同异常类型的处理结合到同一except
子句中:
try:
# some bad code
except (User.DoesnotExist, SomeOtherException):
# error handling code