我需要在 JavaScript 中的 `throw` 之后 `return` 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26067190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Do I need to `return` after `throw` in JavaScript?
提问by Matthew
I'm throwing an Errorfrom a method of mine that I want an early exit from, as below:
我正在Error从我想要提前退出的方法中抛出一个,如下所示:
// 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.
我需要return;在我的后面加一个声明throw吗?它现在对我有用。如果它是多余的,我宁愿不把它放进去,但我不能确定不同的浏览器会做什么。
回答by Rob M.
You do not need to put a returnstatement after throw, the returnline will never be reached as throwing an exception immediately hands control back to the caller.
您不需要在 之后放置return语句throw,return因为抛出异常会立即将控制权交还给调用者,因此永远不会到达该行。

