可以在Js中将try/catch转换为if/else吗?



只是好奇是否有可能将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);
}

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

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

最新更新