操作順序加上高階思想

如果沒有 try catch 塊,未定義的函式將丟擲錯誤並停止執行:

undefinedFunction("This will not get executed");
console.log("I will never run because of the uncaught error!");

將丟擲錯誤而不是執行第二行:

// Uncaught ReferenceError: undefinedFunction is not defined

你需要一個類似於其他語言的 try catch 塊,以確保捕獲該錯誤,以便程式碼可以繼續執行:

try {
    undefinedFunction("This will not get executed");
} catch(error) {
    console.log("An error occured!", error);
} finally {
    console.log("The code-block has finished");
}
console.log("I will run because we caught the error!");

現在,我們已經發現了錯誤並且可以確保我們的程式碼將要執行

// An error occured! ReferenceError: undefinedFunction is not defined(…)
// The code-block has finished
// I will run because we caught the error!

如果我們的 catch 塊發生錯誤怎麼辦?

try {
    undefinedFunction("This will not get executed");
} catch(error) {
    otherUndefinedFunction("Uh oh... ");
    console.log("An error occured!", error);
} finally {
    console.log("The code-block has finished");
}
console.log("I won't run because of the uncaught error in the catch block!");

我們不會處理 catch 塊的其餘部分,除了 finally 塊之外,執行將暫停。

// The code-block has finished
// Uncaught ReferenceError: otherUndefinedFunction is not defined(…)

你總是可以巢狀你的 try catch 塊..但是你不應該因為那會變得非常混亂..

try {
    undefinedFunction("This will not get executed");
} catch(error) {
    try {
        otherUndefinedFunction("Uh oh... ");
    } catch(error2) {
        console.log("Too much nesting is bad for my heart and soul...");
    }
    console.log("An error occured!", error);
} finally {
    console.log("The code-block has finished");
}
console.log("I will run because we caught the error!");

將捕獲前一個示例中的所有錯誤並記錄以下內容:

//Too much nesting is bad for my heart and soul...
//An error occured! ReferenceError: undefinedFunction is not defined(…)
//The code-block has finished
//I will run because we caught the error!

那麼,我們怎樣才能抓住所有錯誤!?對於未定義的變數和函式:你不能。

此外,你不應該在 try / catch 塊中包裝每個變數和函式,因為這些是簡單的示例,只有在你修復它們之前才會發生一次。但是,對於你知道的物件,函式和其他變數,但你不知道它們的屬性或子程序或副作用是否存在,或者你希望在某些情況下出現某些錯誤狀態,你應該抽象出錯誤處理以某種方式。這是一個非常基本的示例和實現。

沒有受保護的方式來呼叫不受信任或異常丟擲方法:

function foo(a, b, c) {
    console.log(a, b, c);
    throw new Error("custom error!");
}
try {
    foo(1, 2, 3);
} catch(e) { 
    try {
        foo(4, 5, 6); 
    } catch(e2) {
        console.log("We had to nest because there's currently no other way...");
    }
    console.log(e);
}
// 1 2 3
// 4 5 6
// We had to nest because there's currently no other way...
// Error: custom error!(…)

並有保護:

function foo(a, b, c) {
    console.log(a, b, c);
    throw new Error("custom error!");
}
function protectedFunction(fn, ...args) {
    try {
        fn.apply(this, args);
    } catch (e) {
        console.log("caught error: " + e.name + " -> " + e.message);
    }
}

protectedFunction(foo, 1, 2, 3);
protectedFunction(foo, 4, 5, 6);

// 1 2 3
// caught error: Error -> custom error!
// 4 5 6
// caught error: Error -> custom error!

我們捕獲錯誤並仍然處理所有預期的程式碼,儘管語法稍有不同。無論哪種方式都可行,但是當你構建更高階的應用程式時,你將需要開始考慮抽象錯誤處理的方法。