-1

The following code when executed doesn't result in argument( i.e : Divide by Zero is not permitted ) being printed. It only gives built in error message from- ZeroDivisionError. So, whats the use of user defined arguments when built in error messages are available.

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)
Butters
  • 21
  • 7

2 Answers2

0

Make your Exception generic works:

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)

And if your want to define your own exception, follow this way:

# 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

You can find this template here: Proper way to define python exceptions

RandomEli
  • 1,527
  • 5
  • 30
  • 53
  • It works now. The spelling of division in ZeroDivisonError is wrong!. But after fixing it, argument is getting printed now. – Butters Jul 15 '16 at 15:20
  • There's nothing wrong with ZeroDivisionError, but what he wrote in line is a string. This should be an object from the Exception class, not a string. – RandomEli Jul 15 '16 at 15:20
  • @LingboTang print accepts objects also and print them successfully – frist Jul 15 '16 at 15:22
  • @frist Again, it isn't a problem with print(). However, the syntax he used to throw the exception is not correct. – RandomEli Jul 15 '16 at 15:25
  • @Butters If you want to accept this answer, you can click the check sign. – RandomEli Jul 15 '16 at 15:26
  • @LingboTang you mean catch (or except)? He doesn't throw (raise) exception it's been raised by division operation :-) – frist Jul 15 '16 at 15:28
  • @frist Here, as what he mentioned in his own answer: `except "ZeroDivisonError",argument:`, which is a syntax of `except ,arg` should be changed to the pattern: `except , arg` – RandomEli Jul 15 '16 at 15:33
0

The spelling of "ZeroDivisonError" is incorrect and moreover it shouldnt be in "". Correct line:

    except ZeroDivisionError,argument:
    print "Divide by Zero is not permitted \n ",argument
Butters
  • 21
  • 7