Lesson 14 of 15
Error Handling
Graceful Error Handling
A robust interpreter should report errors clearly instead of crashing. We need to handle:
Types of Errors
| Error | Example | Message |
|---|---|---|
| Undefined variable | print x; | Error: undefined variable 'x' |
| Division by zero | print 10 / 0; | Error: division by zero |
| Undefined function | print foo(1); | Error: undefined function 'foo' |
Implementation Strategy
Instead of returning undefined or crashing, we'll throw descriptive errors and catch them at the top level:
if (node.type === "Identifier") {
if (!(node.name in env)) {
throw new Error("undefined variable '" + node.name + "'");
}
return env[node.name];
}
For division by zero:
if (node.op === "/") {
if (r === 0) throw new Error("division by zero");
return l / r;
}
Catching Errors
Wrap the top-level interpret call:
function interpret(input) {
try {
// tokenize, parse, evaluate
} catch (e) {
console.log(e.message);
}
}
Your Task
Add error handling for undefined variables, division by zero, and undefined function calls. The interpreter should print the error message and continue to the next program.
Node.js loading...
Loading...
Click "Run" to execute your code.