在这种情况下我应该如何插入 try-except

How should I insert try-except in this scenario

Task1

Write a script that reads a string from STDIN and raise ValueError exception if the string has more than 10 characters or else prints the read string.

我是这样写代码的

a = input("Enter a string")
if(len(a) > 10):
    raise ValueError
else:
    print(a)

Task2

Use try ... except clauses. Print the error message inside except block.

我现在对如何在这里使用 try-except 感到困惑,因为要在 except 块中打印任何消息,程序必须在 try 块处失败。

我的输入将是 PythonIsAmazing

您可以将整个内容包装在 try ... except 中,如下所示:

a = input("Enter a string: ")

try:
    if(len(a) > 10):
        raise ValueError
    print(a)
except ValueError:
    print("String was longer than 10 characters")

或者,如果您有很多不同的 ValueErrors 可能会被引发,您可以给每个单独的错误消息:

a = input("Enter a string: ")

try:
    if(len(a) > 10):
        raise ValueError("String was longer than 10 characters")
    print(a)
except ValueError as e:
    print(e)

例如:

Enter a string: test
test

Enter a string: PythonIsAmazing
String was longer than 10 characters