美文网首页html5
js try catch 的使用

js try catch 的使用

作者: 前端小旋风 | 来源:发表于2019-07-22 16:33 被阅读0次

比如嘞

function test(){
    return new Promise((r,j) => {
        setTimeout(() => {
            j('@')
        }, 2000);
    })
}

test().catch((err) => {
    console.log(err) // @
})

如果用await的话就要用try catch 来获取catch的返回值了

async function test2(){
    try {
        let res = await test();
    }catch (e){
        console.log(e) // @
    }
}

test2();

try catch 的嵌套

function test(str){
    return new Promise((r,j) => {
        setTimeout(() => {
            j(str)
        }, 2000);
    })
}


async function test2(){
    try {
        let res = await test('@');
        try {
            let res = await test('!')
        }catch (e){
            console.log(e,'!') // 没有输出
        }
    }catch (e){
        console.log(e,'@') // @@
    }
}

test2();

内部的try因为外部的try出现异常,代码运行直接跳转到catch中

function test(str){
    return new Promise((r,j) => {
        setTimeout(() => {
            if(str == '@'){
                r(str)
            }else {
                j(str)
            }
        }, 2000);
    })
}


async function test2(){
    try {
        let res = await test('@');
        try {
            let res = await test('!')
        }catch (e){
            console.log(e,'!') // !!
        }
    }catch (e){
        console.log(e,'@')
    }
}

test2();

如果外部try 没有出现异常会继续向下执行

我建了一个前端微信交流群,欢迎大家加入,qq中转群号:1076484243

相关文章

  • 18.try-catch

    1.try-catch http://caibaojian.com/w3c/js/js_try_catch.htm...

  • 错误处理

    try ... catch ... finally JavaScript 使用 try ... catch ......

  • 开发过程中遇到的问题

    try catch 在接口中使用注意 使用 try catch 的使用无论是在 try 中的代码还是在 catch...

  • js try catch 的使用

    比如嘞 如果用await的话就要用try catch 来获取catch的返回值了 try catch 的嵌套 内部...

  • js异常捕获

    一、js异常捕获的两种方式: 1、try...catch2、window.onerror try...catch ...

  • 语句

    几个简单的js变量作用域 try -catch 语句 try 后面必须有 finally 或者 catch 因而有...

  • iOS的@try、@catch()、@finally,相信用到的

    iOS的@try、@catch()、@finally使用--转载iOS @try @catch异常机制--转载iO...

  • Java代码优化

    优化实践 1.try{}catch(){}使用 1)查询中不要使用try{}catch(){}语句 2)循环中不要...

  • 第九章:违例差错控制

    目录 1.说明&个人理解 2.违例使用1(try catch) 3.违例使用2(try throw catch) ...

  • Js try catch

    在try里面发生错误,不会执行错误后try里面的代码 try里面代码出错,会执行catch里面的代码,try代码没...

网友评论

    本文标题:js try catch 的使用

    本文链接:https://www.haomeiwen.com/subject/tdrwlctx.html