Python 中的异常的参数


异常可以包含一个参数,此参数是提供有关问题更多信息的值。参数的内容因异常而异。你可以通过在 except 子句中提供一个变量来捕获异常的参数,如下所示 −

try:
   You do your operations here;
   ......................
except ExceptionType, Argument:
   You can print value of Argument here...

如果你编写代码来处理单个异常,则可以在 except 语句中让变量跟在异常名称之后。如果你正在捕获多个异常,则可以在异常的元组后跟一个变量。

此变量接收异常的值,其中大部分包含异常的原因。该变量可以接收一个值或以元组形式接收多个值。此元组通常包含错误字符串、错误编号和错误位置。

示例

以下是单个异常的示例 −

 现场演示

#!/usr/bin/python
# Define a function here.
def temp_convert(var):
   try:
      return int(var)
   except ValueError, Argument:
      print "The argument does not contain numbers\n", Argument
# Call above function here.
temp_convert("xyz");

输出

产生以下结果 −

The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'

更新日期:2020 年 1 月 30 日

4K+ 观看

开启您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.