面试题答案
一键面试同步代码执行错误处理方式
try...catch
块:用于捕获同步代码块中抛出的错误。- 错误回调:一些函数接受一个回调函数,其中第一个参数为错误对象。例如,
fs.readFile
异步读取文件时可以通过回调处理错误。但本题聚焦同步,故不展开此方式。
使用try...catch
块捕获和处理同步函数抛出的错误示例
function divide(a, b) {
if (b === 0) {
throw new Error('除数不能为零');
}
return a / b;
}
try {
const result = divide(10, 0);
console.log(result);
} catch (error) {
console.error('捕获到错误:', error.message);
}
try...catch
在处理文件读取同步操作错误时的应用场景
在Node.js中,fs.readFileSync
用于同步读取文件。若文件不存在、权限不足等情况会抛出错误,可通过try...catch
捕获并处理。
const fs = require('fs');
try {
const data = fs.readFileSync('nonexistentFile.txt', 'utf8');
console.log(data);
} catch (error) {
if (error.code === 'ENOENT') {
console.error('文件不存在');
} else {
console.error('其他错误:', error.message);
}
}
在此场景中,try...catch
能确保在文件读取同步操作出错时,程序不会崩溃,而是优雅地处理错误,向用户或开发者提供有意义的反馈信息。