Your function sum
returns the sum a+a
or undefined if the catch
block is entered. You would like to know if the catch
block is accessed: it will never be (or in some very special cases...)
It will never throw an error whatever input you may have on sum
the try
: the reason is that the value of a
is coerced implicitly to make the concatenation operation possible:
const sum = (a) => {
try {
return a + a
} catch (e) {
console.log('error: ', e)
}
}
console.log(sum()) // NaN
console.log(sum(() => {})) // () => {}() => {}
console.log(sum(NaN)) // NaN
console.log(sum(undefined)) // NaN
console.log(sum(true)) // 2
console.log(sum({})) // [object Object][object Object]
console.log(sum([])) //
console.log(sum(1)) // 2
.as-console-wrapper { max-height: 100% !important; top: 0; }
So maybe you would like to test if the input is an integer:
const sum = (a) => {
if(Number.isInteger(a)) {
return a + a;
} else {
throw 'Parameter is not an integer';
}
}
Which will result in:
sum() // "Uncaught Parameter is not an integer"
sum(() => {}) // "Uncaught Parameter is not an integer"
sum(NaN) // "Uncaught Parameter is not an integer"
sum(undefined) // "Uncaught Parameter is not an integer"
sum(true) // "Uncaught Parameter is not an integer"
sum({}) // "Uncaught Parameter is not an integer"
sum([]) // "Uncaught Parameter is not an integer"
sum(1) // 2
Here's an example using try...catch
:
const sum = (a) => {
if (Number.isInteger(a)) {
return a + a;
} else {
throw 'Parameter is not an integer';
}
}
try {
sum('no good argument');
} catch (e) {
console.log(e);
}