简体   繁体   English

在涉及引发异常的函数中我做了什么错?

[英]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 and arg2 have been converted to floats. 说明:编写一个函数validate_input(string),该函数采用格式为'command arg1 arg2'的命令字符串,并返回该对('command',[arg1,arg2]),其中arg1和arg2已转换为浮点数。 If the command is not one of 'add', 'sub', 'mul', or 'div', it must raise InvalidCommand. 如果该命令不是'add','sub','mul'或'div'之一,则它必须引发InvalidCommand。 If the arguments cannot be converted to floats, it must raise InvalidCommand. 如果参数不能转换为浮点数,则必须引发InvalidCommand。

Typical inputs and outputs: 典型的输入和输出:

validate_input('add 2 3') -> ('add' [2. , 3.]) validate_input('add 2 3')->('add'[2.,3.])

validate_input('hahahaha 2 3') -> Raises InvalidCommand() validate_input('hahahaha 2 3')->引发InvalidCommand()

validate_input('add six 3') -> Raises InvalidCommand() validate_input('增加六个3')->引发InvalidCommand()

Here is my code: 这是我的代码:

class InvalidCommand(Exception):
    pass

def validate_input(string):
"""
validate_input(str) -> (str, [float])

If string is a valid command, return its name and arguments.
If string is not a valid command, raise InvalidCommand

Valid commands:
  add x y
  sub x y
  mul x y
  div x y

Arguments x and y must be convertable to float.

"""
    inlist = string.split(' ')
    commands = []
    strdigits = []
    floats = []
    output = []
    for x in inlist:
        if x.isdigit():
            strdigits.append(x)
        else:
            commands.append(x)
    for x in commands:
        try:
            x == 'add' or 'sub' or 'mul' or 'div'
            output.append(x)
        except ValueError:
            return InvalidCommand(ValueError)
    for x in strdigits:
        try:
            float(x)
            floats.append(float(x))
            output.append(floats)
        except ValueError:
            return InvalidCommand(ValueError)
    return tuple(output)

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 要引发异常,请使用raise ExceptionType(parameter) ,而不要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. 由于InvalidCommand是自定义的Exception类型(Python中未包含),因此在使用InvalidCommand之前应为其定义类。 This class definition could go near the top of the python program file, and only needs to appear once. 这个类定义可以放在python程序文件的顶部附近,只需要出现一次即可。

For more, see Python docs -- errors and exceptions 有关更多信息,请参见Python文档-错误和异常

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. 第37行(用于循环),您是立即从floats追加值,这导致它将float列表两次追加到output变量。 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. 对于输入mul 5 6 ,它正在返回('mul', [5.0, 6.0], [5.0, 6.0]) ,因此要做的第一件事是在循环后放置output.append(floats)

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. 从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. 处理无效的command值。

As Paul suggested in comments, use raise Exception to raise an exception. 如Paul在评论中所建议,请使用raise Exception引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM