javascript - 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);
解决方案
在开始计算之前确保这s
是一个。string
要么转换s
为string
:
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));
}
推荐阅读
- javascript - NodeJs Express app.get 处理查询和参数
- angular - Microsoft 使用 Angular 登录
- json - Azure 中 LogicApp 集成中的映射文件
- c - 为什么 init_pair 在 COLOR_PAIRS 范围的一半内失败?
- html - 使用 Bootstrap 4 在全屏高度响应 div 之后放置 html
- sass - 无法在 Gulp 中完成简单的 Sass 任务
- javascript - 当打字光标离开输入文本字段时如何触发功能?
- powershell-4.0 - 使用 get-childitem 获取文件列表的最有效方法是什么
- python - Tensorflow:具有相同随机种子的不同结果
- vim - vim中的vscode仿真