diveDylan / blog

My blog, detail is in the issues list
2 stars 0 forks source link

try和catch的深入了解 #46

Open diveDylan opened 4 years ago

diveDylan commented 4 years ago

这一块没有找到比较规范的资料,所以把js抽象成一个框架,以设计者和使用者的角色来尝试理解

### 代码编译成如下
function TCFStack(tStack, cStack, fStack ) {
     const t = tStack()
    let c 
    <innerStack>.onerror = () => {
      c =  cStack()
   }
  const f = fStack()
   return t ? (f ? f : t) : c

}

验证一下抽象的理解

function testTCF() {
    try {
      console.log('try')
      return 'try'
    } catch(e) {
       console.log('catch')
      return 'catch'
    } finally {
       console.log('finally')
      return 'finally'
   }
}
testTCF() // 'try' 'finally' 'finally'
diveDylan commented 4 years ago

异常捕获的时机

try {
   setTimeout(() => {
     throw new Error(1)
   },0)
}catch(e) {
   console.log(e)
 }
// 并没有进入console,无法捕获timer的异步回调
try {
     Promise.resolve(1).then(() => {
       throw new Error(1)
   })
} catch(e) {
   console.log(e)
}
// 没有捕获
 setTimeout(() => {
    try {
       throw new Error(1)
    } catch(e) {
      console.log('timeout error', e)
   }
   },0) 
// ✅
 Promise.resolve(1).then(() => {
       try {
         throw new Error(1)
        } catch(e) {
            console.log('err', e)
        }

   })
// ✅

按我的理解,try catch是全局宏任务代码块一部分,抽象成一个宏任务,该宏任务执行完毕前的异常都可以捕获,执行后的就无法捕获