
stanley
4/7/2026

Exception 是在程式執行期間發生的異常狀況,用來中斷正常流程
if (true {
console.log("Hello");
}
// SyntaxError: Unexpected token '{'console.log(b)
// Uncaught ReferenceError: b is not defined// 範例 1:對非函式呼叫
let num = 123;
num();
// TypeError: num is not a function
// 範例 2:對 null 或 undefined 操作屬性
let obj = null;
console.log(obj.name);
// TypeError: Cannot read property 'name' of null
// 範例 3:對非陣列使用陣列方法
let notArray = {};
notArray.push(1);
// TypeError: notArray.push is not a function
// 範例 4:對不可寫入的值賦值
const PI = 3.14;
PI = 3;
// TypeError: Assignment to constant variable.let arr = new Array(-1);
// RangeError: Invalid array length在錯誤發生時,控制程式行為的一種機制
f/else 是判斷已知條件,try/catch 是控制未知錯誤。
// 底層:資料庫操作
function getUser(id) {
if (!id) {
throw new Error("User ID is required"); // 拋出錯誤給上層
}
return { id, name: "Alice" };
}
// 中層:業務邏輯
function processUser(id) {
const user = getUser(id); // 這裡可能會 throw
console.log("Processing user:", user.name);
}
// 上層:API handler
function apiHandler(req) {
try {
processUser(req.id); // 捕捉所有下層錯誤
console.log("Success");
} catch (error) {
console.error("API Error:", error.message);
// 可以決定回傳 400 / 500 或其他 fallback
}
}
// 測試
apiHandler({});
// Console output:
// API Error: User ID is requiredtry。catch 捕捉特定例外類型,做回應(例如:記錄 log、回傳錯誤訊息、重試)。try {
// attempt to execute this code
} catch (exception) {
// this code handles exceptions
} finally {
// this code always gets executed
}