以下代码在执行时不会导致打印参数(即:不允许除以零)。它只提供来自-零除错误。那么,当内置错误消息可用时,用户定义的参数有什么用。
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)
使你的异常通用工作:
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
你可以在这里找到这个模板:定义python异常的正确方法
"ZeroDivisonError"的拼写不正确,而且它不应该在"中。正确行:
except ZeroDivisionError,argument:
print "Divide by Zero is not permitted n ",argument