Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 views
in Technique[技术] by (71.8m points)

try 的 finally 有什么使用场景?

请问以下两个代码有什么区别? try 的 finally 有什么使用场景?

try {
    throw  'x'
} catch {

} finally {
  console.log(1)
}
try {
    throw  'x'
} catch {

}
console.log(1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你这样写当然没有区别,不过如果在try里面有return,在catch里面有return或者throw的话,如果有finally,则finally代码仍然被执行,如果没有finally,把代码写在try/catch之外,则这些代码不会被执行。

try {
    throw  'x'
    return 1;//此时console.log(1)会被执行
} catch {
    return -1;//此时console.log(1)会被执行
} finally {
  console.log(1)
}
try {
    throw  'x'
    return 1;//此时console.log(1)不会被执行
} catch {
    return -1;//此时console.log(1)不会被执行
}

  console.log(1)

如果要总结的话,就是finally里面的代码在离开try/catch的时候被调用,不管是顺序执行离开,还是return离开,throw离开,只要离开了try/catch,都会调用finally里面的代码。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...