捕获python中的特定错误

时间:2018-09-16 13:01:23

标签: python django python-3.x exception error-handling

我正在尝试捕获特定的异常:

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'>

为什么会这样?如何捕获特定的异常?

1 个答案:

答案 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


参考
1. Python: One Try Multiple Except