try catch finally

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"

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容