Skip to content Skip to sidebar Skip to footer

What Did I Do Wrong In My Function Involving Raising An Exception?

The instructions: Write a function validate_input(string) which takes a command string in the format 'command arg1 arg2' and returns the pair ('command', [arg1, arg2]), where arg1

Solution 1:

There are multiple errors,so I will address the question in the title: what are the errors with raising an exception ?

To raise an exception, use raise ExceptionType(parameter), not return

Like this:

 class InvalidCommand(Exception):
     pass

 try:
      s = raw_input("Enter a number:")
      x = float(s)
 except ValueError:
      raise InvalidCommand(s+" is not a number")

Note that Custom exception types always need to be defined somewhere. Since InvalidCommand is a custom Exception type (not included in Python), there should be a class definition for InvalidCommand before using it. This class definition could go near the top of the python program file, and only needs to appear once.

For more, see Python docs -- errors and exceptions


Solution 2:

Line #37 (for loop), You are appending the value immediately from floats, which is causing it to append the list of float twice to the output variable. For input mul 5 6, it is returning ('mul', [5.0, 6.0], [5.0, 6.0]), so the first thing you need to do it put output.append(floats) after the loop.

for x in strdigits:
    try:
        float(x)
        floats.append(float(x))
    except ValueError:
        return InvalidCommand(ValueError)
output.append(floats)

Secondly this is wrong way to do it,

x == 'add' or 'sub' or 'mul' or 'div'

Check these output from Python shell.

>>> x = 'fas'
>>> x == 'add' or 'sub' or 'mul' or 'div'
'sub'
>>> x in ['add','sub','mul','div']
False
>>> bool('sub')
True

I hope it's clear, so change your condition to

if x in ['add','sub','mul','div']:
    output.append(x)
else:
    raise InvalidCommand(ValueError)

to deal with invalid command value.

As Paul suggested in comments, use raise Exception to raise an exception.


Post a Comment for "What Did I Do Wrong In My Function Involving Raising An Exception?"