Search code examples
pythonpython-3.xstringvalueerrortry-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.

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


Solution

  • 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