[問題探討]js中的錯誤捕獲和拋出try-catch-finally throw

版權說明:

本文參考了《JavaScript高級程序設計(第3版)》第17章 ‘錯誤處理與調試’ 的相關內容,並在其基礎上做了拓展,如有侵權請版權方聯繫博主刪除。
博主聯繫方式:[email protected]

問題:

捕獲錯誤和拋出錯誤的時機是什麼?

分析:

捕獲錯誤和拋出錯誤的時機:應該捕獲那些你確切地知道該如何處理的錯誤,捕獲錯誤的目的在於避免瀏覽器以默認方式處理它們(比如不友好的提醒、代碼終止,界面卡住或者崩潰);而拋出錯誤的目的在於提供錯誤發生具體原因的消息,以提示我們更準確的處理他們。

方法:

捕獲錯誤:try-catch-finally
拋出錯誤:throw

基本語法:

一,捕獲錯誤

try{     
	// 可能會導致錯誤的代碼 
	// 如果發生錯誤則停止執行,並反饋error對象給catch
	// 然後執行catch裏面的代碼
} catch(error){ 
    // 在錯誤發生時怎麼處理 
    // 錯誤發生時纔會執行的代碼
} finally {
	// 無論錯誤與否都會執行的代碼
	// 包括try catch裏面的return語句也會被忽略
}

二,拋出錯誤

 // 拋出一個通用錯誤
 throw new Error('This is a error message');

demo示例:

一,捕獲錯誤

<html lang="zh-en">
    <head>
    </head>
    <body>
        <script>
            console.log(desOfTom);
            console.log('This is the next!');
        </script>
    </body>
</html>

以上代碼會報錯並導致程序終止,而且不會執行最後的‘console.log(‘This is the next!’);’,解析結果如下:
在這裏插入圖片描述
如果我們想讓程序繼續執行,我們可以引入try catch :

<html lang="zh-en">
    <head>
    </head>
    <body>
        <script>
            try {
                console.log(desOfTom);
            } catch(err) {
                console.log(err.message)
            } finally {
                console.log('tom is handsome!');
            }
            console.log('This is the next!');
        </script>
    </body>
</html>

以上代碼會終止執行try裏面報錯的部分,通過控制檯拋出錯誤消息,並繼續執行finally和try catch之後的‘console.log(‘This is the next!’);’代碼,代碼執行結果如下:
在這裏插入圖片描述
二,拋出錯誤
在遇到 throw 操作符時,代碼會立即停止執行(同瀏覽器默認錯誤處理方式)。僅當有 try-catch 語句捕獲到被拋出的值時,代碼纔會繼續執行。 通過使用某種內置錯誤類型,可以更真實地模擬瀏覽器錯誤。每種錯誤類型的構造函數接收一個參數,即實際的錯誤消息。下面是一個例子:
代碼:

<html lang="zh-en">
    <head>
    </head>
    <body>
        <script>
            throw new Error('This is a error message');
            console.log('This is the next!');
        </script>
    </body>
</html>

運行結果:
在這裏插入圖片描述
以上代碼代碼拋出了一個通用錯誤,帶有一條自定義錯誤消息。瀏覽器會像處理自己生成的錯誤一樣, 來處理這行代碼拋出的錯誤。換句話說,瀏覽器會以常規方式報告這一錯誤,並且會顯示這裏的自定義錯誤消息,同時會終止代碼執行。像下面使用其他錯誤類型,也可以模擬出類似的瀏覽器錯誤。

throw new SyntaxError("I don’t like your syntax."); 
throw new TypeError("What type of variable do you take me for?"); 
throw new RangeError("Sorry, you just don’t have the range."); 
throw new EvalError("That doesn’t evaluate."); 
throw new URIError("Uri, is that you?"); 
throw new ReferenceError("You didn’t cite your references properly."); 

在創建自定義錯誤消息時常用的錯誤類型是 Error、RangeError、ReferenceError 和TypeError。
下面是一個try-catch捕捉throw錯誤的例子,try-catch會像捕捉瀏覽器自己生成的錯誤一樣捕捉throw拋出的錯誤:
代碼:

<html lang="zh-en">
    <head>
    </head>
    <body>
        <script>
            try {
                throw new Error('This is a error message');
            } catch(err) {
                console.log(err.message)
            } finally {
                console.log('tom is handsome!');
            }
            console.log('This is the next!');
        </script>
    </body>
</html>

運行結果:
在這裏插入圖片描述
點擊此超鏈接跳轉到Tom哥的博文分類和索引頁面
Tom哥的博客博文分類和索引頁面地址:https://blog.csdn.net/tom_wong666/article/details/84137820

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章