如果抛出错误-JavaScript,是否可以重新尝试try-catch块?
假设我有一个函数,它获取一个随机数,然后返回该数是否满足条件,如果不满足条件,则抛出一个错误:如果抛出错误-JavaScript,是否可以重新尝试try-catch块?,javascript,function,loops,error-handling,try-catch,Javascript,Function,Loops,Error Handling,Try Catch,假设我有一个函数,它获取一个随机数,然后返回该数是否满足条件,如果不满足条件,则抛出一个错误: const randFunc = () => { let a = Math.floor(Math.random() * 10) if(a === 5){ return a } else { throw new Error('Wrong Num') } } 我想知道的是,我是否可以循环使用这个函数,直到得到“5” try { randFunc() } c
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()继续抛出,这段代码将导致一个无休止的循环。类似的东西可能适合您
let success = false;
while (!success) {
try {
randFunc();
success = true;
} catch { }
}
如果randFunc()继续抛出,此代码将导致无止境循环。只是一个标准的无止境循环:
const randFunc=()=>{
设a=Math.floor(Math.random()*10);
如果(a==5){
返回a;
}否则{
抛出新错误('Error Num');
}
}
函数直到成功(){
while(true){
试一试{
返回randFunc();
}捕获{}
}
}
log(直到成功())代码>只是一个标准的无止境循环:
const randFunc=()=>{
设a=Math.floor(Math.random()*10);
如果(a==5){
返回a;
}否则{
抛出新错误('Error Num');
}
}
函数直到成功(){
while(true){
试一试{
返回randFunc();
}捕获{}
}
}
log(直到成功())代码>您可以设置一个持续尝试某项功能直到其工作:
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()
}
}
您可以设置一个持续尝试某项功能直到它起作用:
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()
}
}
把它放到一个循环中。把它放到一个循环中。非常感谢,这有助于解决它。很高兴知道我没有想到一个循环!非常感谢,这有助于解决它很好地知道没有想到一个而循环!