The fact is that after the matched throw , execution is immediately interrupted and immediately proceed to catch .

 console.log("128 THROW САМ ПО СЕБЕ БЕЗ TRY НЕ РАБОТАЕТ, хотя пример на странице 128 Фленагана есть"); var f132 = function (a,b) { if (a > b) { throw new Error ("заданная ошибка 1"); return a } if (a == b) { throw new Error ("заданная ошибка 2"); return 7 } else { throw new Error ("заданная ошибка 3"); return 9 } //catch (er) { console.log (er); } //SyntaxError: catch without try =>9 } console.log (f132(16,15)); 

But what about the page 128 of the Flenagan textbook, which states that you can use throw ?

screenshot

  • I understand that throw works everywhere, but it is intercepted only in a try-catch block. If an exception is not intercepted at this level, then it is thrown to a level higher .... i.e., if the level is not higher than catch and it will not be found so, then the exception is considered as an error and will be reported to the user (that is, execution on the code in the presence of throw and absence at levels above catch, the code "stops", gives an error in the console)? That is, throw DOESN'T make sense if there is no catch in the code? - Esenin
  • That is, throw, when there is no catch in the code, will it just stop the execution of the code? - Esenin
  • Just type in javascript throw in Google and read a few articles on it to figure it out. For example, this one with MDN . And ask questions only on truly incomprehensible moments. - Regent
  • return immediately after throw simply useless, because it is unreachable. At first I was afraid that it was written in this book (even if for clarity, it’s said that the return code will never come to this ). - Regent

2 answers 2

Using throw without catch is the only reasonable option in modular code, since Often the throw task in a function is to handle an error in a way that is defined outside this function.

 function factorial(n) { if (n < 0) { throw new Error("Factorial argument must be non-negative"); } if (n == 0) { return 1; } return n * factorial(n - 1); } try { // factorial ничего не знает об этом блоке console.log(factorial(-10)); } catch { console.log("Oops!"); } 

If you execute a throw outside a try block, the interpreter will consider this a system error and process as it sees fit (depending on whether it is a browser or a node).


Precedent from history:

I told Dennis that about half of the code I wrote for Multics was error handling code. He replied: “We have dropped all this. If an error occurs, we have a procedure called panic, and if it is called, the computer freezes and you shout: “Hey, restart it!”.

wiki

    Of course not: throw interrupts the execution of the code.