Preparing your workspace
Error handling lets programs respond to unexpected situations in a controlled way.
Real applications can fail because of invalid input, network problems, unavailable data, or programming mistakes. JavaScript provides try, catch, and finally for handling exceptions. The try block contains code that may fail, catch handles the error, and finally runs whether the operation succeeds or fails. Developers can also throw custom Error objects when a condition should be treated as a failure. Good error handling should provide useful information without exposing sensitive internal details to users.
A course page can catch an API failure and show 'Unable to load course. Please try again.' instead of leaving the page in a broken state.
async function loadCourse() {
try {
const response = await fetch('/api/course');
if (!response.ok) {
throw new Error('Course request failed');
}
return await response.json();
} catch (error) {
console.error(error);
return null;
} finally {
console.log('Request finished');
}
}The function either returns course data or returns null after logging the error, and the finally block runs in both cases.