Refer to the code below:
01 let first = 'Who';
02 let second = 'What';
03 try {
04 try {
05 throw new Error('Sad trombone');
06 } catch (err) {
07 first = 'Why';
08 throw err;
09 } finally {
10 second = 'When';
11 }
12 } catch (err) {
13 second = 'Where';
14 }
What are the values for first and second once the code executes?
Initial values:
first = 'Who'
second = 'What'
Execution:
Inner try/catch/finally:
Line 05: throw new Error('Sad trombone');
Control goes to the inner catch.
Inner catch (lines 06--08):
catch (err) {
first = 'Why';
throw err;
}
first is set to 'Why'.
The error is rethrown.
Inner finally (lines 09--11):
finally {
second = 'When';
}
finally runs whether or not there was an error.
second becomes 'When'.
After inner finally, the rethrown error continues to propagate to the outer catch.
Outer catch (lines 12--14):
} catch (err) {
second = 'Where';
}
Because the inner try rethrew, the outer catch runs.
It sets second = 'Where'.
Final values:
first was changed to 'Why' in the inner catch and never changed again.
second became 'When' in the inner finally, and then 'Where' in the outer catch.
So:
first is 'Why'
second is 'Where'
Option B is correct.
Concepts: nested try/catch/finally, rethrowing errors, order of execution for catch vs finally, variable mutation through error propagation.
Currently there are no comments in this discussion, be the first to comment!