Can you convert a try/catch into a if/else in Js?

Issue

Just curious if it was possible to turn a try/catch into an if/else and what the syntax would be like. Below is some of my code from an express js app I’m building for saving and deleting notes.

// Retrieves notes from storage
  getNotes() {
    return this.read().then((notes) => {
      let parsedNotes;
      // Below parsedNotes will add the parsed individual note to the stored notes array
      try {
        parsedNotes = [].concat(JSON.parse(notes));
      } catch (err) {
        // Returns empty array if no new note is added
        parsedNotes = [];
      }
      // Returns array
      return parsedNotes;
    });
  }
  // Adds note to array of notes
  addNote(note) {
    // Construction of note prior to save
    const { 
      title, 
      text 
    } = note;
    // Adds a ID to the new note
    const newNote = { 
      title, 
      text, 
      id: uuidv4() 
    };
    // Gets notes, adds new notes, then will update notes with new note
    return this.getNotes()
      .then((notes) => [...notes, newNote])
      .then((updatedNotes) => this.write(updatedNotes))
      .then(() => newNote);
  }

I’m new to programming and was just curious if it was possible and how it would be done. Thanks!

Solution

Not really, no. if/else are appropriate, for instance, if a function returns null or undefined on error. Exceptions behave differently from that: when an exception is thrown, it stops execution and jumps to the catch block that’s associated with the closest try block in which the exception was thrown. If there’s no try block at all, the program (normally) crashes. You can’t check for exceptions with if/else because it will jump out of the if block containing it and either directly go to the catch block or crash the program if there is no try block, without executing any of the code inbetween.

Answered By – Ætérnal

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published