javascript throw Error 和 console.error 有什么区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25377115/
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
What is the difference between throw Error and console.error
提问by Michal Hainc
What is the difference between these two statements, and is there a good reason to use one over the other?
这两个语句之间有什么区别,是否有充分的理由使用一个而不是另一个?
throw Error("msg");
console.error("msg");
In my limited experience, I've only really seen throw Error()
used. Is there any particular reason why?
以我有限的经验,我只见过真正throw Error()
使用过的。有什么特别的原因吗?
Also, is there an equivalent to console.warn()
in the same fashion?
另外,是否有等效console.warn()
于相同的方式?
回答by Michal Hainc
throw ...
raises an exception in the current code block and causes it to exit, or to flow to next catch
statement if raised in a try
block.
throw ...
在当前代码块中引发异常并导致它退出,或者catch
如果在try
块中引发则流到下一个语句。
console.error
just prints out a red message to the browser developer tools javascript console and does not cause any changes of the execution flow.
console.error
只是向浏览器开发人员工具 javascript 控制台打印出一条红色消息,不会导致执行流程发生任何变化。
回答by Pramod S. Nikam
Some of the Differences are:
一些差异是:
throw Error("msg"):
抛出错误(“msg”):
- Stops js execution.
- Mostly used for code handling purpose.
- Can alter main flow of execution.
- This syntax is mostly same for all browser as this is specified and validated by W3C.
- 停止 js 执行。
- 主要用于代码处理目的。
- 可以改变主要的执行流程。
- 此语法对于所有浏览器几乎相同,因为这是由W3C指定和验证的。
console.error("msg"):
控制台错误(“味精”):
- It just shows output in Red color at Browser console
- It is mostly used to print values for debugging purpose.
- Cannot harm main flow of execution.
This Syntax sometimes vary according to vendor browser and not standardized by W3C.
i.e. For IE accepted syntax is
window.console.debug("msg")
- 它只是在浏览器控制台以红色显示输出
- 它主要用于打印用于调试目的的值。
- 不能损害主要执行流程。
此语法有时会因供应商浏览器而异,并且未由W3C标准化。
即对于 IE 接受的语法是
window.console.debug("msg")
回答by Michael Aaron Safyan
Throw is for actually changing the control flow (jumping out of the current context and up to an error handler) for handling errors programmatically. The console statement is just for debugging and printing text to the error console. You may see them used in conjunction, for example:
Throw 用于实际更改控制流(跳出当前上下文并到达错误处理程序)以编程方式处理错误。控制台语句仅用于调试和打印文本到错误控制台。您可能会看到它们结合使用,例如:
var doSomethingDangerous = function(response) {
if (isMalformed(response)) {
throw Error('Response is malformed.');
}
process(response);
};
var sendAsyncRequest = function() {
var request = buildAsyncRequest();
request.sendThen(function (response) {
try {
doSomethingDangerous(response);
} catch (e) {
console.error(e);
doSomeAdditionalErrorHandling();
}
});
};