[Tutor] A problem involving exception handling, need suggestions to improve further

Cameron Simpson cs at cskk.id.au
Wed Nov 4 16:15:23 EST 2020


On 04Nov2020 07:45, Mats Wichmann <mats at wichmann.us> wrote:
>On 11/4/20 7:42 AM, Manprit Singh wrote:
>>In the below written mail , we are only raising an exception . I need 
>>to
>>make a program that can end normally while displaying a message "Wrong
>>value of order entered"  without error  if a user provides inappropriate
>>input  in a function call like ser_gen(9, -1).
>
>You wrap the call to the function in a try block, and handle the 
>exception the way you want it. In this case you should remove the 
>prints in the function and instead print after calling the function.

Just to elaborate a bit on Mats' advice, it is uncommon for functions 
themselves to use print() calls (unless their purpose is actually 
"output").

Instead, functions usually return values or raise exceptions.

This lets the calling code decide what should happen.

So the outermost, interactive, part of your programme might look like 
this:

    while True:
        value_s = input("Enter a value: ")
        try:
            value = int(value_s)
        except ValueError:
            print("Not an int! Received", repr(value_s))
            continue
        try:
            result = func(value)
        except ValueError as e:
            print("Invalid value %r: %s" % (value, e))
        else:
            print("Result =", result)

and func would look like:

    def func(x):
        if x < 1:
            raise ValueError("invalid value for x, should be >=1")
        return x * 2

You can see:
- func is cleaner: it returns the value or raises a ValueError exception 
  _with an explaination_
- it does not print anything - it has no opinion about what should 
  happen to its value
- the main programme is where "policy" decisions about output and 
  behaviour on errors takes place

Also notice that because the ValueError includes an explaination, it is 
useful to include the exception in the complaint you print in the main 
programme. All the exceptions you raise should include some explaination 
of why they were raised, usually as short as possible which still making 
the failed condition clear.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list