【问题标题】:try-catch statement interrupt try-block as soon as exception is thrown一旦抛出异常,try-catch 语句就中断 try-block
【发布时间】:2019-03-02 07:21:02
【问题描述】:

研究:

根据MDN web docs

try...catch 语句标记要尝试的语句块,并且 指定响应,是否应引发异常。

如果我理解正确,整个 try-block 将被执行。这个SO 的帖子证实了我自己。

我的问题:

是否可以在抛出异常后立即中断 try 块以进入 catch 块?

是的:如何实现这种行为?
否:是否有其他方法可以实现此行为?

【问题讨论】:

  • If I understand this correctly the entire try-block will be executed 不,我不知道你从哪里得到这个想法。如果try 块中有三行代码并且第一行抛出异常,那么其他两行将被跳过并执行catch。链接的答案也声称。如果没有异常,则catch不会被执行。
  • 如果抛出异常,try中尚未执行的行将不会运行。

标签: javascript exception-handling try-catch


【解决方案1】:

try {
  console.log('omg');
  throw new Error('omg');
  console.log('ahhhhhh!!!!!');
} catch {
  console.log('caught');
}

我认为 JS 做你想做的事。链接的 SO 用于 Java。

【讨论】:

  • 公平地说,它与我见过的任何具有try...catch 的语言的行为方式相同。
  • 我想,但不确定。
【解决方案2】:

您链接的 SO 帖子是关于 Java 的,而不是 Javascript。 所以那里的答案可能不适用。

据我所知,catch 块将在抛出错误的那一刻被触发。 你可以随时抛出错误:

try {
  console.log( 'before error: this should log' );
  throw new Error( 'Trigger catch!' );
  console.log( 'after error: this should not log' );
}
catch( error ) {
  console.log( `catch block got the error: ${ error.message }` );
}

【讨论】:

  • The SO post you linked is about Java, not Javascript. So the answers there might not be applicable. 它们是,因为构造的工作方式相同。唯一显着的区别是,在 Java 中,您可以选择要捕获的异常,例如,只有 NullPointerException 而不是 InvalidArgumentException。在这种情况下,这并不重要。此外,链接问题中接受的答案已经说明Instruction flow is interrupted when any exception occurs anywhere.
  • try/catch 块的工作方式确实相同,但错误对象接口仍然存在差异。因此,如果 OP 没有注意到语言上的差异,他们可能会尝试使用 .getMessage().printStackTrace() 以及 Java 答案中提到的其他方法。因此,我认为有必要向 OP 说明这一点,即并非这些答案中的所有内容都将在 Javascript 中完全相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
  • 2012-08-06
  • 2014-09-09
  • 2012-02-20
相关资源
最近更新 更多