Can we use continue and break statements within try and catch blocks
eg.,
for(let i=0; i< arr.length; i++) {
try {
// Some condition
continue;
}
catch(e) {
continue;
}
}
Example:
for (let i = 0; i < 10; i++) {
console.log(`Iteration ${i} start`);
try {
console.log(`Iteration ${i} try block`);
if (i === 1) {
throw new Error('error');
} else if (i === 2) {
continue;
} else if (i === 3) {
break;
}
} catch (e) {
console.log(`Iteration ${i} catch block`);
continue;
}
console.log(`Iteration ${i} end`);
}
This prints:
Iteration 0 start
Iteration 0 try block
Iteration 0 end
Iteration 1 start
Iteration 1 try block
Iteration 1 catch block
Iteration 2 start
Iteration 2 try block
Iteration 3 start
Iteration 3 try block
An even better example:
for (let i = 0; i < 10; i++) {
console.log(`Iteration ${i} start`);
try {
console.log(`Iteration ${i} try block start`);
if (i === 1) {
throw new Error('error');
} else if (i === 2) {
throw new Error('continue');
} else if (i === 3) {
throw new Error('break');
}
console.log(`Iteration ${i} try block end`);
} catch (e) {
console.log(`Iteration ${i} catch block`);
if (e.message === 'break') {
console.log(`Iteration ${i} catch block: break`);
break;
} else if (e.message === 'continue') {
console.log(`Iteration ${i} catch block: continue`);
continue;
}
console.log(`Iteration ${i} catch block end`);
}
console.log(`Iteration ${i} end`);
}
Output:
Iteration 0 start
Iteration 0 try block start
Iteration 0 try block end
Iteration 0 end
Iteration 1 start
Iteration 1 try block start
Iteration 1 catch block
Iteration 1 catch block end
Iteration 1 end
Iteration 2 start
Iteration 2 try block start
Iteration 2 catch block
Iteration 2 catch block: continue
Iteration 3 start
Iteration 3 try block start
Iteration 3 catch block
Iteration 3 catch block: break
As you can see it all works as expected for both break
and continue
inside of try
and catch
blocks alike.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With