I am new to learning JavaScript and sort of stuck up while learning exception handling. I have understood the thing that whenever an exception occurs , it is thrown using "throw" keyword and similarly it is caught using "catch" block.
But what I am unable to understand is that , I have a small , simple code that demonstrates simple Exception handling technique, and in that code whenever I change the place of the catch block, I get different outputs. Here is the simple code and its different o/p s depending upon where I place the catch block.
function lastElement(array) {
if (array.length > 0)
return array[array.length - 1];
else
throw "Can not take the last element of an empty array.";
}
function lastElementPlusTen(array) {
return lastElement(array) + 10;
}
try {
print(lastElementPlusTen([]));
}
catch (error) {
print("Something went wrong: ", error);
}
the o/p that I get here is as expected :
Something went wrong: Can not take the last element of an empty array.
now when I add the try/catch block around the function lastElementPlusTen: like this
function lastElement(array) {
if (array.length > 0)
return array[array.length - 1];
else
throw "Can not take the last element of an empty array.";
}
try {
function lastElementPlusTen(array) {
return lastElement(array) + 10;
}
}
catch (error) {
print("Something went wrong: ", error);
}
print(lastElementPlusTen([]));
now the o/p that I get here is :
Exception: "Can not take the last element of an empty array."
the "something went wrong" from the catch block is not printed.
why is this so??similarly when I place the try/catch block around different pieces of code (for ex: around the first function , body of the lastElementPlusTen function etc) I get different o/p s. why is this happening. How does exception handling work??