Working with Modules and Handling Exceptions
Estimated study time: 7 minutes. Two habits that separate fragile scripts from production-ready code.
Two skills quickly separate beginner code from production-ready code: organizing logic into modules, and handling things going wrong through exception handling.
Working with Modules
A module is simply a file (or group of files) that encapsulates a specific piece of functionality and exposes only what other parts of the app need. Good module design follows a few habits:
- One responsibility per module — a
authmodule handles authentication, not also formatting dates. - Export only what's needed externally; keep internal helper functions private.
- Avoid circular dependencies — module A importing module B which imports module A again.
Handling Exceptions
Things fail at runtime — a network call times out, a file doesn't exist, user input is malformed. Exception handling lets your program respond to these failures without crashing entirely.
try {
const data = JSON.parse(userInput);
processData(data);
} catch (error) {
console.error('Failed to process input:', error.message);
showUserFriendlyError();
} finally {
hideLoadingSpinner();
}
Best Practices for Exceptions
- Catch only what you can meaningfully handle — don't swallow errors silently.
- Use specific error types/messages so debugging doesn't turn into guesswork.
- Always clean up resources (connections, spinners, locks) in a
finallyblock. - Log enough context to reproduce the issue later.
💡 Tip: Well-structured modules make exceptions easier to handle too — when each module has a single responsibility, you know exactly where to expect (and catch) specific kinds of errors.