tl;drtry-catch如果一个任务可能在多个事件中失败,例如 API 获取、划分、解析等,那么使用多个块或一个块来捕获它们是否有意义?
我有一个执行两项任务的功能。
- 从 API 中获取两个数字,
a然后b. - 履行
a/b
这是实际问题的简化版本。我想问一下如何处理异常,因为任务可能在两个步骤中的任何一个上失败:
- 提取本身失败。
a/b导致错误,因为b = 0.
我可以想到两种方法。
选项一
try {
const data = getFromAPI();
const result = data[0] / data[1];
return result;
} catch (err) {
// Catch all errors here...
}
选项二
try {
try {
const data = getFromAPI();
} catch(err) {
// Catch all API errors here..
}
const result = data[0] / data[1];
return result;
} catch (err) {
// Catch division errors here...
}