在js中也可以使用try/catch語法,把可能發生異常的代碼使用try包裹起來,然后在catch中對異常進行處理,處理后就不會影響后面代碼的執行。
const a = null try { const b = JSON.parse(a) console.log(a.name) } catch (e) { console.log("發生異常:" + e) }
上面是系統拋出的異常,也可以自定義拋出異常:
const a = null try { if (a == null || a == '') { throw '值為空' } else { console.log(a) } } catch (e) { console.log("發生異常:" + e) }
