如果抛出错误,是否可以重试 try-catch 块 - JavaScript?

Is it possible to re-try a try-catch block if error is thrown - JavaScript?

假设我有一个获取随机数的函数,然后 returns 该数字是否满足条件,如果不满足则抛出错误:

const randFunc = () => {
 let a = Math.floor(Math.random() * 10)
 
 if(a === 5){
     return a
  } else {
     throw new Error('Wrong Num')
 }
}

我想知道我是否可以循环执行此函数直到得到“5”

try {
    randFunc()
} catch {
    //if error is caught it re-trys
}

谢谢!

类似的内容可能适合您

let success = false;
while (!success) {
  try {
    randFunc();
    success = true;
  } catch { }
}

如果 randFunc() 不断抛出,此代码将导致无限循环。

只是一个标准的无限循环:

const randFunc = () => {
 let a = Math.floor(Math.random() * 10);
 
 if(a === 5){
     return a;
  } else {
     throw new Error('Wrong Num');
 }
}

function untilSuccess() {
  while (true) {
    try {
      return randFunc();
    } catch {}
  }
}

console.log(untilSuccess());

或递归选项:

const randFunc = () => {
  let a = Math.floor(Math.random() * 10);

  if (a === 5) {
    return a;
  } else {
    throw new Error('Wrong Num');
  }
}

function untilSuccess() {
  try {
    return randFunc();
  } catch {
    return untilSuccess();
  }
}

console.log(untilSuccess());

根据您的重试次数,这个可能会破坏您的筹码(不过这不是什么大问题)。

您可以设置一个 recursive function 来不断尝试直到成功为止:

const randFunc = () => {
 let a = Math.floor(Math.random() * 10)
 
 if(a === 5){
     return a
  } else {
     throw new Error('Wrong Num')
 }
}

getfive()

//getfive is recursive and will call itself until it gets a success
function getfive(){
  try{
    randFunc()
    console.log('GOT 5!')
  }
  catch(err){
    console.log('DID NOT GET 5')
    getfive()
  }
}