【发布时间】:2020-08-29 10:07:00
【问题描述】:
我有一张地图,并试图根据以“id”形式传递的 key 来检索 value。但是在某些情况下,传递的“id”是无效的,即它不存在于 Map 中,这反过来会导致应用程序崩溃。是否抛出错误导致此问题?我尝试使用 try-catch 进行试验,但它仍然继续出现故障,即屏幕在检测到此错误时停止加载。不确定我是否正确编写了 try-catch。在这种情况下,我该如何最好地处理这个问题,以阻止应用程序出现故障并继续加载屏幕。
失败的方法:
this.hmItems = {}; //Map<Integer,Item>
Address.prototype.getItem = function (id) {
var item = this.hmItems[id];
if (!item)
throw new Error("'Illegal argument: id=" + id);
return item;
};
另一种失败的方法:
this.hmItems = {}; //Map<Integer,Item>
Address.prototype.getItem = function (id) {
try {
var item = this.hmItems[id];
if (!item) throw "illegal id!!!!!!!!!";
return item;
} catch(err) {
//log exception
}
}
【问题讨论】:
标签: javascript dictionary hashmap key-value