在JavaScript中“抛出”后是否需要“返回”?

时间:2021-02-13 01:49:00

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.

我需要退货吗?我把后声明吗?现在,它对我很有效。如果这是多余的,我宁愿不把它放进去,但我不能确定不同的浏览器会做什么。

1 个解决方案

#1


89  

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.

您不需要在抛出之后放置一个返回语句,返回线将永远不会到达,因为抛出异常将立即将控制权交还给调用者。

#1


89  

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.

您不需要在抛出之后放置一个返回语句,返回线将永远不会到达,因为抛出异常将立即将控制权交还给调用者。