-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)
7
  • Please, format your code appropriately Commented Jul 15, 2016 at 14:55
  • That's not how exceptions and exception handling work. Commented Jul 15, 2016 at 15:09
  • except "ZeroDivisonError",argument is invalid Python. Commented Jul 15, 2016 at 15:09
  • @Rogalski: It's valid, just absolutely not what you want to do. Commented Jul 15, 2016 at 15:10
  • duplicate of stackoverflow.com/questions/4690600/…? Commented Jul 15, 2016 at 15:11

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

7 Comments

It works now. The spelling of division in ZeroDivisonError is wrong!. But after fixing it, argument is getting printed now.
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.
@LingboTang print accepts objects also and print them successfully
@frist Again, it isn't a problem with print(). However, the syntax he used to throw the exception is not correct.
@Butters If you want to accept this answer, you can click the check sign.
|
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.