Do I need to `return` after `throw` in JavaScript?
JavascriptExceptionError HandlingJavascript Problem Overview
I'm throwing an Error
from a method of mine that I want an early exit from, as below:
// No route found
if(null === nextRoute) {
throw new Error('BAD_ROUTE');
}
Do I need to put a return;
statement after my throw
? It works for me, for now. If it's superfluous I'd rather not put it in, but I can't be sure what different browsers might do.
Javascript Solutions
Solution 1 - Javascript
You do not need to put a return
statement after throw
, the return
line will never be reached as throwing an exception immediately hands control back to the caller.
Solution 2 - Javascript
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.