如果在try中出现了错误,try里面出现错误语句的后面的代码不再执行,而是跳到catch中处理错误信息,然后继续执行后面的代码;如果try里没有出现 错误,那么不走catch,直接执行后面的代码。

 console.log(1);
        console.log(2);
        try{
            console.log(a);
        }catch(e){
            console.log(e);
        }
        console.log(3);
        console.log(4);
        console.log(5);            

throw是抛出异常的语句,后面跟上一个对象,即错误消息对象。一般使用「new Error(' 错误消息')」来创建,也支持任意对象。

try{
                throw new Error('手动抛出的异常!');
            }catch(e){
                console.log(e);
            }

 

                function showMessage (msg) {
                //要求传入的参数是一个字符串,如果不是抛出异常;
                if(typeof(msg)!='string'){
                    throw new Error('传入的参数不是一个字符串!');
                }
                console.log(msg);
            }
            try{
                showMessage('123');
                showMessage(123);
            }catch(e){
                console.log(e);
            }                    

 

相关文章:

  • 2022-12-23
  • 2021-08-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-19
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-07
  • 2021-10-29
  • 2021-11-08
  • 2021-06-01
  • 2022-12-23
相关资源
相似解决方案