js中的错误捕获和抛出try-catch-finally thr

2019-08-02  本文已影响0人  来碗鸡蛋面

原创声明

本文系作者辛苦码字所得,欢迎分享和转载,但请在明显位置注明作者的如下信息:
笔名:来碗鸡蛋面
简书主页:https://www.jianshu.com/u/4876275b5a73
邮箱:job_tom@foxmail.com
CSDN ID:tom_wong666

版权说明:

本文参考了《JavaScript高级程序设计(第3版)》第17章 ‘错误处理与调试’ 的相关内容,并在其基础上做了拓展,如有侵权请版权方联系博主删除。
博主联系方式:job_tom@foxmail.com

问题:

捕获错误和抛出错误的时机是什么?

分析:

捕获错误和抛出错误的时机:应该捕获那些你确切地知道该如何处理的错误,捕获错误的目的在于避免浏览器以默认方式处理它们(比如不友好的提醒、代码终止,界面卡住或者崩溃);而抛出错误的目的在于提供错误发生具体原因的消息,以提示我们更准确的处理他们。

方法:

捕获错误: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>

运行结果:

上一篇下一篇

猜你喜欢

热点阅读