在python中使用多个异常 [英] Using multiple exceptions in python

查看:49
本文介绍了在python中使用多个异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在python中使用多个异常?像下面的代码:

Is there a way to use multiple exceptions in python? Like code below:

try:
   #mycode
except AttributeError TypeError ValueError:
   #my exception

我的意思是如何互相使用 AttributeError TypeError ValueError ?

What I mean is how to use AttributeError TypeError ValueError with each other?

推荐答案

使用元组:

try:
   # mycode
except (AttributeError, TypeError, ValueError):
   # catches any of the three exception types above

引用引用 try 语句文档:

Quoting the reference try statement documentation:

try 套件中发生异常时,将开始搜索异常处理程序.此搜索依次检查except子句,直到找到与异常匹配的子句.
[...]
对于带有表达式的except子句,将对该表达式求值,并且如果结果对象与该异常兼容",则该子句将与该异常匹配.如果对象是例外对象的类或基类,或者是包含与例外兼容的项目的元组,则该对象与例外兼容.

When an exception occurs in the try suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception.
[...]
For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is "compatible" with the exception. An object is compatible with an exception if it is the class or a base class of the exception object or a tuple containing an item compatible with the exception.

强调我的.

这篇关于在python中使用多个异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆