异常可以具有一个参数,该参数是一个值,它提供有关该问题的其他信息。参数的内容因异常而有所不同。您可以通过在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'