首页 > 解决方案 > Try 可以工作,但 Catch 不能在 Javascript 函数中工作,如下所述

问题描述

在下面的函数中,Catch 不起作用。无法得到错误信息。

function reverseString(s) {
  var ary = s.split("");
  ary.reverse();
  try {
    console.log(ary.join(""));
  } catch (err) {
    console.log(err);
  }
}
reverseString(1234);

标签: javascripterror-handlingtry-catch

解决方案


在开始计算之前确保这s是一个。string

要么转换sstring

function reverseString(s) {
  var ary = String(s).split("");
  ary.reverse();
  try {
    console.log(ary.join(""));
  } catch (err) {
    console.log(err);
  }
}
reverseString(1234);

s如果不是字符串,则抛出自定义错误:

function reverseString(s) {
  if (typeof s !== "string") throw Error("s is not a string");
  // or
  // if (typeof s.split !== "function") throw Error("split is not supported");
  var ary = s.split("");
  ary.reverse();
  try {
    console.log(ary.join(""));
  } catch (err) {
    console.log(err);
  }
}
try {
  reverseString(1234);
} catch (err) {
  console.log("Error: " + (err && err.message));
}
try {
  reverseString("1234");
} catch (err) {
  console.log("Error: " + (err && err.message));
}


推荐阅读