catch blocks and handle them gracefully.
Error handling is an important part of software development, so
Consider the following code snippet and describe what would happen when you try to run it.
Code snippet as a picture
How will the
try/catch blocks behave? What will be logged to the console? (think well, then click for the answer and explanation)
So, we have 2 variables and 2
try/catchblocks that supposedly catch errors and put them into
Then, the content of errors is analyzed, compared and the comparison result is logged to the screen.
First, let’s determine what’s inside of
e2. To do that, we need to check the code in the
tryblocks. Both trying to get to
undefined.lengthwill throw an error as neither
These errors will be caught in the catch blocks as
eand then assigned to the variables
The content of these errors will be a bit different. If we were to log
e.messageto the screen in the catch block, we would see the following:
Cannot read property 'length' of null Cannot read property 'length' of undefined
.split(' ')gives us the first words of these sentences which is
Cannotin both cases. So ultimately, the program can be simplified to:
console.log('Cannot' === 'Cannot')
The expression in the
console.logwill be evaluated as
trueand logged to the screen