As others have mentioned above, if you are not throwing an Error object, then you must have try/catch blocks to trap these objects and handle them appropriately or else be in a world of hurt for debugging.
However, when it comes to throwing Errors for non-error handling purposes like controlling program flow, this may be a helpful way to utilize throw
without an Error.
When using throws to control program flow, it can be inefficient in any language as the runtime will often do a lot of heavy lifting to unwind call stack information and serialize the data so its available to the user land scope. By avoiding Error creation, you can avoid this performance hit. The key is that you must have a handler up the call stack that knows how to handle this situation. For instance if you throw {isHardStop: true, stopCode: SOME_CODE}
and design the handlers to detect this, you may be able to flatten out some of your code or choose cleaner syntax.
Your handler for this ladder case could be structured like:
try { ... } catch(thr) {
if(!thr){
// Is not Error or Json - Handle accordingly
} else if(thr.isHardStop){
// Handle the stop
} else {
// Most likely a real error. Handle accordingly
}
}
throw new Error
andthrow someObject
in JavaScript?