I don't understand why finally?
-
Hello everyone! I'm learning js, now I've finished a lesson about exceptions. So, why use finally after try / catch, if it will be executed anyway? For example, why write
try {} catch {} finally { alert('В любом случае') }
... if you can do
try {} catch {} alert('После try/catch, но тоже в любом случае')
Is this just a syntactic trick to make it easier to read, or is there really some difference? Well, except for the scope (you can create an anonymous block without a condition, just a literal). I don't understand, explain)JavaScript Ariana Delgado, Jun 16, 2020 -
In try catch, there may be an exit from this construction, and then in the second case (without finally) we will not be able to execute the block that we absolutely need to execute.Adalyn Richardson
-
There is a difference in this case:
const func = () => {
try {
return "try value"
} catch(e) {}
return "after try"
}
console.log(func()) // try value
const func = () => {
try {
return "try value"
} catch(e) {}
finally {
return "finally value"
}
return "after try"
}
console.log(func()) // finally value
finally is executed first, and this can be critical in a functionAnonymous
2 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!