美文网首页
try catch finally

try catch finally

作者: Time_Notes | 来源:发表于2024-02-14 07:52 被阅读0次

    In a try...catch...finally scenario, the finally block is always executed irrespective of an error is thrown or not within the try block. Also, Control flow statements like return in the finally block overwrite any completion values of the try block or catch block.

    In this example, for "BFE.dev" JSON.parse will throw error and control goes to the catch block and "errored" is returned. However, since finally block always executes and we return str from it, the final returned value is "BFE.dev" that gets logged

    Similarly, for "123", the try block tries to return, but finally block's return value is returned instead.


    const prettify=(str)=>{

    try{

        if(typeofstr==='string'){

            JSON.parse(str)

            return"prettified"

        }

    }catch(e){

        return"errored"

    }finally{

        return    str

    }

    }console.log(prettify('BFE.dev'))// "BFE.dev"

    console.log(prettify('123'))// "123"

    相关文章

      网友评论

          本文标题:try catch finally

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