你能在Js中将try/catch转换成if/else吗?

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

只是好奇是否可以将 try/catch 转换为 if/else 以及语法是什么样的。下面是我为保存和删除笔记而构建的 express js 应用程序中的一些代码。

// 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);
  }

我是编程新手,只是很好奇这是否可能以及如何完成。谢谢!

不是,不是。 if/else 是合适的,例如,如果函数 returns nullundefined 出错。异常的行为与此不同:抛出异常时,它会停止执行并跳转到与抛出异常的最近的 try 块相关联的 catch 块。如果根本没有 try 块,程序(通常)会崩溃。你不能用 if/else 检查异常,因为它会跳出包含它的 if 块,要么直接转到 catch 块,要么使程序崩溃如果没有 try 块, 没有 执行中间的任何代码。