try {Block} -catch statement
try catch
The statement will first execute the code block wrapped by try, and judge whether to enter catch
the code block according to the execution result of the code block.
- If
catch
the code block also throws an exception, it will overridetry
the exception thrown in the statement
function test (){
try {
throw new Error('error1');
} catch (e) {
throw new Error('error2');
}
}
- If the code block has a return result, the execution result of the statement
catch
will be overwritten when an exception is thrown .try
Otherwise,Block
it returns undefined because an exception is thrown. l
function test (){
try {
return 0
} catch (e) {
return 1
}
}
test() // 0
function test1 (){
try {
throw new Error()
return 0 // 这里不会执行到
} catch (e) {
return 1
}
}
test1() //1
try {Block} -finally statement
- If
finally
the code block also throws an exception, it will overridetry
the exception thrown in the statement
function test (){
try {
throw new Error('error1');
} finally {
throw new Error('error2');
}
}
test() //'error2'
try
finally
The code wrapped with and will be executed in sequence, and the returned results B and F will be recorded at the same time. If F has a return value (normal or abnormal return), the result of F will be returned, otherwise the result of B will be returned
function test (){
try {
throw new Error()
} finally {
return 1
}
}
test() // 1
function test2 (){
try {
return 0
} finally {
}
}
test2() // 0
function test3 (){
try {
return 0
} finally {
return 1
}
}
test3() // 1
try {Block} catch -finally statement
It is equivalent to the combined execution of try catch and try finally, first execute the processing result of try catch and then merge the result with finally, the exception in finally will cover the exception and return in try/catch
function test() {
var a = 1;
try {
return a;
} finally {
++a;
}
}
test() // 1
function test1() {
var a = 1;
try {
return a;
} finally {
++a;
return a;
}
}
test1() // 2
function test2() {
var obj = {a:1};
try {
return obj;
} finally {
++obj.a;
}
}
test2().a // 2
function test3() {
var obj = {a:1};
try {
return obj.a;
} finally {
++obj.a;
}
}
test1() // 1
Summarize:
catch
exceptionstry
override exceptions for andreturn
catch
return
The exception of overridetry
andreturn
finally
The exception oftry/catch
overrides the exception of andreturn
finally
return
The exception of overridetry/catch
andreturn
try/catch/finally
The code in orreturn
after will not be executed