用户定义并在异常中构建参数

时间:2016-07-15 14:46:21

标签: python exception

执行时的以下代码不会导致打印参数(即:不允许除以零)。它只提供内置的错误信息 - ZeroDivisionError。因此,当内置错误消息可用时,是否使用了用户定义的参数。

print "Enter the dividend"
dividend=input()
print "Enter the divisor"
divisor=input()

try:
    result=dividend/divisor
except "ZeroDivisonError",argument:
    print "Divide by Zero is not permitted \n ",argument # Argument not getting printed
else:   
    print "Result=%f" %(result)

2 个答案:

答案 0 :(得分:0)

制作您的例外通用作品:

dividend=int(input("Enter the dividend: "))
divisor=int(input("Enter the divisor: "))

try:
    result=dividend/divisor
except Exception,argument:
    print "Divide by Zero is not permitted \n ",str(argument) # Argument not getting printed
else:   
    print "Result=%f" %(result)

如果您想定义自己的例外,请按照以下方式:

# Define a class inherit from an exception type
class CustomError(Exception):
    def __init__(self, arg):
        # Set some exception infomation
        self.msg = arg

try:
    # Raise an exception with argument
    raise CustomError('This is a CustomError')
except CustomError, arg:
    # Catch the custom exception
    print 'Error: ', arg.msg

您可以在此处找到此模板:Proper way to define python exceptions

答案 1 :(得分:0)

" ZeroDivisonError"的拼写是不正确的,而且它不应该在""。 正确的行:

    except ZeroDivisionError,argument:
    print "Divide by Zero is not permitted \n ",argument