Example parsing the execution rules of try catch and finally in js
- 2021-07-24 09:43:00
- OfStack
try: The statement tests the code block for errors, and puts the code that may go wrong here
catch: Only when an error occurs in the code block in try, the code here will be executed, and the parameter err records the error message of the code in try
finally: Code executes with or without exception
try{
console.log(0);
}catch (err){
console.log(1);
console.log(hello);
}finally {
console.log(2);
}
// The final results are printed separately 0 2
/*
try{
a.b.c();
}catch (e){
console.log(1);
console.log(hello);
}finally {
console.log(2);
}
*/
// The final results are printed separately 1 2 Report an error :hello is not defined
/*
try{
a.b.c();
}catch (e){
console.log(1);
try{
console.log(hello);
}catch (e){
console.log(3);
}
}finally {
console.log(2);
console.log(word);
}
*/
// The final results are printed separately 1 3 2 Report an error :word is not defined
/*
try{
a.b.c();
}catch (e){
console.log(1);
console.log(hello);
}finally {
console.log(2);
console.log(word);
}*/
// The final results are printed separately 1 2 Report an error :word is not defined
Summary:
When the code in try reports an error, the code in catch will be executed, and the code in finally will always be executed
In catch and finally, normal code is executed from top to bottom
If only the code in catch is wrong, report the error in catch
Errors in finally will be reported if both catch and finally fail