https://toitlang.org/ logo
catch behavior unclear
# help
k
when using a catch, I get exception:
Copy code
CODE_INVOCATION_FAILED
Called block with too few arguments.
Got: 0 Expected: 1.
Target:
     testList.<block>.<block>  test.toit:32:24
I want to catch OUT_OF_BOUNDS EXCEPTION error. But I get exceptions with valid indices. What is wrong here ?
k
When you use
catch:
, you're passing a block to the called method. That block is called without any arguments, so if the block you provide expects one or more arguments, you'll get an exception.
Your block can take arguments in two ways.
One is explicit:
catch: | x y | ...
.
Here your block expects two arguments, so it will not work.
k
Copy code
testList:
  DATA ::= [1,2]


  2.repeat:         // works 
    d := DATA[it]
    print "$it: $d"

  2.repeat:
    d := null 
    e := catch --trace : d = DATA[it]
    print "$it: $d"
k
The other and more subtle one is the implicit one introduced when the block uses
it
.
So here you want the outer block to take an argument, but not the inner one.
2.repeat: | index | catch --trace: DATA[index]
k
Thank you: I'm starting to understand it ...
... and it already works !
... so i had a problem with the right use of 'it' ?
Copy code
main:
  testList

testList:
  DATA ::= [1,2]

  // force out of bounds error - but catch it
  3.repeat: | index |
    d := null 
    e := catch : d = DATA[index]
    print "$index: $d"
Now it works - as expected ! Nevertheless, what is the difference in using 'it' and 'index' ?
k
Using
it
, adds an implicitly defined parameter to the innermost block. In your case that was the block passed to
catch:
.
After your change, you no longer use
it
from within the block passed to
catch:
, so it doesn't get the unwanted parameter.
When you use
index
or any other name you explicitly give your block parameters, you do not get any implicitly defined parameters for the block passed to
catch:
. Instead, the compiler knows that
index
refers to the parameter in the block passed to
repeat:
.
k
aha : from now on I will avoid 'it' and use only explicit parameters 😉
k
I mostly use
it
for "small" blocks. That's where it really shines.