Pregunta

I am fairly new to google apps script and I came across this issue while trying out tutorial on "Your First Custom Function".

=in2mm(1) -> 25.4
=in2mm(2) -> 50.8
=in2mm() -> #ERROR (error: input must be a number (line 6))
=in2mm(pi()) -> 79.7964534011807
=in2mm(a) -> #NAME? (error: Unknown range name a)
=in2mm(*) -> #ERROR (error: Parse error)

I am trying to understand the usage of "throw" function in google apps script. How is it able to produce the "input must be a number" in my line 3 whereas line 5 and 6 produces some other results?

¿Fue útil?

Solución

You could make the error message more explicit by adding some case handling like this :

function in2mm(inNum) {
  // Function to convert from INCHES to MILLIMETERS
  var outNum = 0;     // this will hold the answer
  var factor = 25.4;  // multiply input by this factor to get output
    if (inNum == "") {  // check to make sure input is a number
    throw ("error: input must not be empty");  // throw an exception with the error message
    }else if (typeof inNum != "number") {  // check to make sure input is a number
    throw ("error: input must be a number (now it is a "+typeof inNum+")");  // throw an exception with the error message
}
  outNum = inNum * factor;  // calculate the answer
  return outNum;  // return the answer to the cell which has the formula
}

But the argument has to be 'valid' to be handled by the function... in you example =in2mm(a) a is interpreted as a named region and since you don't have a region called 'a' it thows an error before trying to execute the function. That's why the error message doesn't come from the function itself but from the 'engine' under the spreadsheet.

The other example =in2mm(*) return a Parse error for the same reason, the argument is not valid and in this case it cannot be a range either... you could also try + or - , it will try to calculate something but it can't and again the error message comes from the spreadsheet, not from your function.

Try to use a valid range and change the values in the target cell, you'll see completely different results. For example in A2 write =in2mm(A1) and play with A1

Hoping I made things a (little) bit clearer ;-)

Otros consejos

If you catch the error in your code, then you can throw the error which is what is you see in the third example you provided. As an example, the code would look something like ...

function in2mm(inches){
  if (inches == null){ 
    throw 'input must be a number'; 
  }
}

In the last two examples you provided, the errors are not caught by your function, but are rather caught by Google Spreadsheet.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top