简体   繁体   中英

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.

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. Print the error message inside except block.

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.

My input will be PythonIsAmazing

You can just wrap the whole thing in try... except as follows:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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