Module 1: Error Handling & Modules
Try, Catch & Finally
try {
let result = riskyFunction();
console.log(result);
} catch (error) {
console.log("Something went wrong:", error.message);
} finally {
console.log("This always runs, error or not");
}
Throwing & Custom Errors
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
divide(10, 0);
} catch (error) {
console.log(error.message); // "Cannot divide by zero"
}
// Custom error classes — extend the built-in Error for more specific error types
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function validateAge(age) {
if (age < 0) {
throw new ValidationError("Age cannot be negative");
}
}
try {
validateAge(-5);
} catch (error) {
if (error instanceof ValidationError) {
console.log("Validation failed:", error.message);
} else {
console.log("Unexpected error:", error.message);
}
}
Custom error classes let calling code distinguish between different failure types (validation
error vs network error vs permission error, for example) using instanceof, instead
of parsing error message text.
ES Modules (import/export)
Modules let you split code across multiple files and share specific pieces between them, instead of relying on one giant script or global variables.
// math.js — a module file
export function add(a, b) {
return a + b;
}
export const PI = 3.14159;
// A "default" export — one per file, doesn't need a name to import
export default function multiply(a, b) {
return a * b;
}
// app.js — importing from that module
import multiply, { add, PI } from "./math.js";
console.log(add(2, 3)); // 5
console.log(multiply(2, 3)); // 6
To use modules directly in the browser, the script tag needs type="module":
<script type="module" src="app.js"></script>
CommonJS vs ES Modules
Node.js (covered fully in Module 3) originally used its own module system called CommonJS, which predates ES Modules and looks different:
// CommonJS — math.js
function add(a, b) {
return a + b;
}
module.exports = { add };
// CommonJS — app.js
const { add } = require("./math.js");
// ES Modules — the modern standard, same math.js example
export function add(a, b) {
return a + b;
}
// ES Modules — app.js
import { add } from "./math.js";
Modern Node.js supports both, and ES Modules are now the standard going forward across the whole
JavaScript ecosystem — browser and server alike — but you'll still see CommonJS
(require/module.exports) in a lot of existing Node.js code.