try {
・・・
const divSample1 = document.getElementById('sample1');
if (!divSample1) {
throw new Error('divタグ(id:sample1)が見つかりません');
}
const divSample2 = document.getElementById('sample2');
if (!divSample2) {
throw new Error('divタグ(id:sample2)が見つかりません');
}
・・・
const divSampleN = document.getElementById('sampleN');
if (!divSampleN) {
throw new Error('divタグ(id:sampleN)が見つかりません');
}
・・・
} catch (ex) {
console.error(ex.message);
}
と書きたくないのでNull 合体演算子 (??)を使って
try {
・・・
const divSample = document.getElementById('sample1') ?? throw new Error('divタグ(id:sample1)が見つかりません');}
const divSample = document.getElementById('sample2') ?? throw new Error('divタグ(id:sample2)が見つかりません');}
・・・
const divSample = document.getElementById('sampleN') ?? throw new Error('divタグ(id:sampleN)が見つかりません');}
・・・
} catch (ex) {
console.error(ex.message);
}
と書くと「throw」に赤い下線が付いて「式が必要です。ts(1109)」とエラるので・・・
/**
* 投げだす
* @param {string} msg
*/
const throwMsg = (msg) => {
throw new Error(msg);
}
・・・
try {
・・・
const divSample = document.getElementById('sample1') ?? throwMsg ('divタグ(id:sample1)が見つかりません');}
const divSample = document.getElementById('sample2') ?? throwMsg ('divタグ(id:sample2)が見つかりません');}
・・・
const divSample = document.getElementById('sampleN') ?? throwMsg ('divタグ(id:sampleN)が見つかりません');}
・・・
} catch (ex) {
console.error(ex.message);
}
で誤魔化せた。
式が必要な深い意味は思いつかないので、単に「throw」を式として認識してないダケだろう。
多用するとメンドクサイ事になるのは避けられないが・・・
※{美しくない}
とか言われそう。
心配なのはデバッグ中に式でExceptionすると