简体   繁体   English

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

[英]How should I insert try-except in this scenario

Task1任务1

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.编写一个脚本,从 STDIN 读取一个字符串,如果该字符串超过 10 个字符则引发 ValueError 异常,否则打印读取的字符串。

I wrote the code like this我这样写代码

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

Task2任务二

Use try... except clauses.使用try... except子句。 Print the error message inside except block.在 except 块中打印错误消息。

I am now confused about how to use try-except here because to print any message in except block the program has to fail at try block.我现在对如何在这里使用try-except感到困惑,因为要在except块中打印任何消息,程序必须在try块中失败。

My input will be PythonIsAmazing我的输入将是PythonIsAmazing

You can just wrap the whole thing in try... except as follows:你可以把整个东西包装在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")

Alternatively, if you had lots of different ValueErrors that might be raised, you could give each a separate error message:或者,如果您有许多可能引发的不同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)

Eg:例如:

Enter a string: test
test

Enter a string: PythonIsAmazing
String was longer than 10 characters

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

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