Question

Let a smalltalk msg named "sum" return the sum of elements in an array.

Eg: #(1 2 3 4 5) sum ----> 15

When the input is #(1 2 'a' 3 5) sum. The execution terminates and shows a big exception box. Instead of that how can we gracefully exit the execution by just showing a message. I don't want the big exception window to be shown.

sum
    |sum|
    sum := 0
    self do: [:a | sum := sum + a]
    ^sum

I tried to handle the exception the below way. However, I notice that the execution doesn't terminate in case of invalid input.

sum
    |sum|
    sum := 0
    self do: [:a | 
        (a isInteger) ifFalse:[
            ^[Error signal] on: Exception
            do: [:ex | Transcript show: 'Entered values are non-numeric. Hence comparison is not possible.']
        ]
        sum := sum + a
    ]
    ^sum

If the below code is placed in the workspace, I expected the execution to be terminated at line 2. However, line 3 is also getting executed. |temp| temp := #(1 2 3 'as' 4 5) sum. temp := temp*5.

Was it helpful?

Solution

Changing the sum method to ignore the wrong types in the input Array does not make sense. Furthermore by replacing it with a UI message you completely loose control over what kind of input is acceptable. Rather deal with these exception at the place you use sum:

[ ^ self readInput sum ] 
    on: Error do: [ :error| Transcript show: 'Invalid input provided for sum' ].
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top