JavaScript · Lesson 25 / 32 · English
Error Handling
Understand the idea. Change the code. Build confidence with one focused experiment.
Read this lesson in தமிழ் ↗.
Start with the idea
Errors describe failed operations. Catch errors where you can recover or add useful context; do not silently discard them. finally runs after try/catch for cleanup.
Learning goal: Explain what the example does, predict its result, and change it to solve the practice task.
Step-by-step lesson notes
Error Handling in JavaScript
Errors are inevitable. Good error handling prevents your app from crashing and gives users meaningful feedback.
try / catch / finally
try {
// Code that might throw
const data = JSON.parse("invalid json");
console.log(data);
} catch (error) {
console.error("Error:", error.message);
console.error("Type:", error.name); // "SyntaxError"
} finally {
// Always runs — for cleanup
console.log("Done.");
}
// Optional catch binding (ES2019)
try {
riskyOperation();
} catch {
console.log("Something went wrong");
}Error Types
| Error Type | When it occurs |
|---|---|
| SyntaxError | Invalid JavaScript syntax (parsing) |
| ReferenceError | Using an undeclared variable |
| TypeError | Wrong type (e.g., calling non-function) |
| RangeError | Value out of valid range |
| URIError | Invalid URI encoding/decoding |
| EvalError | Error with eval() function |
Throwing Custom Errors
// Throw built-in error
throw new Error("Something went wrong");
throw new TypeError("Expected a string");
// Custom error class
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
function validateAge(age) {
if (typeof age !== "number") {
throw new ValidationError("Age must be a number", "age");
}
if (age < 0 || age > 150) {
throw new ValidationError("Age must be between 0 and 150", "age");
}
return true;
}
try {
validateAge("old");
} catch (err) {
if (err instanceof ValidationError) {
console.log(`Field: ${err.field} — ${err.message}`);
} else {
throw err; // re-throw unexpected errors
}
}A complete example
Run this complete index.js program in the JavaScript console editor below. The earlier reference fragments may need a browser page or other surrounding setup.
try {
JSON.parse("not valid JSON");
} catch (error) {
console.log(error.name);
} finally {
console.log("Finished checking");
}Predict first. Reveal the expected result.
SyntaxError Finished checking
Make one change. See what happens.
Load the example, change a value, predict the output, and run it again. Use the console output to check your reasoning.
Wait for the editor to load, then load this example and press Run.
Powered by the free OneCompiler editor. Code you run is sent to that external service. Keep personal data and secret keys out of your examples.
Put the idea to work
Practice challenge
Replace the input with valid JSON and log the parsed title.
Reveal the answer and reasoning
Parse '{"title":"JavaScript"}' and log .title. The catch block is skipped; finally still runs.
One mistake to avoid: A synchronous try/catch does not catch a later rejected promise unless that promise is awaited inside the try block.
Your learning checkpoint
- Explain the example in your own words.
- Complete the challenge before revealing its answer.
- Describe the common mistake and how to avoid it.