mardi 10 août 2021

If Try Statement - Javascript [closed]

I stumbled into realizing that this code runs and was curious:

  1. Is this really valid per the spec or does it just happen to work in V8?
  2. Should you ever use this or is it just terribly confusing?

I find it readable/useful without else's involved but it becomes unreadable with an else as you lose meaningful indentation. At that point I think it makes sense to try catch outside the whole block or inside each block depending what you're doing.

//Setup
let count = 0;
function checkStuff() {return count++ === 0;}
function causeError() {throw new Error('Execption!');}

//If-Try - This might be useful sometimes
if (checkStuff()) 
try {causeError()} 
catch (e) {console.log('If-Try Result: ' + e.message);}

//If-Try-Else - This seems impossible to read/understand
if (checkStuff()) 
try {doStuff()} 
catch (e) {console.log(e.message);}
else {console.log('If-Try-Else Result: Else!');}

//If-Try-Else - This seems worse
if (checkStuff()) 
try {doStuff()} 
catch (e) {console.log(e.message);}
else try {causeError()}
catch (e) {console.log('If-Try-Else-Try Result: ' + e.message);}

Aucun commentaire:

Enregistrer un commentaire