2016-07-15 66 views
-1

下面的代码在执行时不会导致打印参数(即:不允许被零除)。它只会提供来自- 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) 
+0

请格式的代码适当 – Tonechas

+0

这不是异常和异常处理是如何工作的。 –

+0

'除了“ZeroDivisonError”,参数'是无效的Python。 –

回答

0

“ZeroDivisonError”的拼写不正确,而且它不应该是我n“”。 正确的路线:

except ZeroDivisionError,argument: 
    print "Divide by Zero is not permitted \n ",argument 
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

+0

ZeroDivisionError有什么问题? – frist

+0

现在有效。 ZeroDivisonError中的分区拼写错误!但是在修复之后,争论现在正在被打印。 – Butters

+0

ZeroDivisionError没有错,但是他在行中写的是一个字符串。这应该是Exception类的一个对象,而不是一个字符串。 –