Note that there are some explanatory texts on larger screens.

plurals
  1. POunderstanding exception handling in JavaScript: get different output when changed the place of try/catch block
    primarykey
    data
    text
    <p>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.</p> <p>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.</p> <pre><code>function lastElement(array) { if (array.length &gt; 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); } </code></pre> <p>the o/p that I get here is as expected :</p> <pre><code>Something went wrong: Can not take the last element of an empty array. </code></pre> <p>now when I add the try/catch block around the function lastElementPlusTen: like this</p> <pre><code>function lastElement(array) { if (array.length &gt; 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([])); </code></pre> <p>now the o/p that I get here is :</p> <pre><code>Exception: "Can not take the last element of an empty array." </code></pre> <p>the "something went wrong" from the catch block is not printed.</p> <p>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??</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload