有没有办法在没有javaScript的情况下定义一个尝试块?
编译器向以下代码投诉:
try {
const newAPI = require("applicationutils");
}
一个月又一个月介绍新API。就我而言,如果有API,我想采取新的行动方案。如果他们不可用,我将使用默认设置。我不需要捕获块。我只想知道是否可能。
如果类不存在,则代码会引发错误,因此必须将其包裹在捕获块中。
不可能使用catch
和/或finally
的try
。根据MDN尝试...捕获:
try
语句由try
块组成,其中包含一个或多个 语句。即使是单个语句,也必须始终使用{}
。在 必须存在至少一个catch
子句或finally
子句。这 为我们提供三种形式的try
语句:try...catch try...finally try...catch...finally
您可以做一些如下所示的操作,其中"块范围"是在您的功能体内定义的,从而有效地实现了您所需的功能。
这些由{ .. }
直接在您的函数中定义,并将词汇/变量范围的新部分引入您的函数,例如,可以定义一个变量,该变量只能在该块的范围内访问。
可以从这些内联块示波器中抛出例外,并将被呼叫堆栈的先前定义的catch
处理程序捕获:
function foo() {
/* Start a block scope in function foo() */
{
/* newAPI only accessible in this block scope */
const newAPI = require("applicationutils");
}
/* Start another block scope, defined in same function foo() */
{
/* newAPI is unique to this block, the newAPI variable name
can be re-used seeing it's unique in the lexical scope */
const newAPI = { getUsers : () => [] };
/* Throwing an exception from block scope is okay - it does not
need to be handled with a catch() clause on this block, and
will be handled by an optional catch() clause lower in the
call stack */
throw new Error('throwing from second block scope in foo()');
}
/* no catch(..) {} clause is syntactically required */
}