JavaScript: Error handling
JavaScript has built-in error types that describe what went wrong, and they help you understand and fix bugs more easily.
When an error happens, JavaScript usually stops running the script unless you handle it properly.
+----------------+----------------------------------------+
| Error Type | When it happens |
+----------------+----------------------------------------+
| SyntaxError | Code is written incorrectly |
| ReferenceError | Using a variable that’s not defined |
| TypeError | Wrong operation on a value type |
| RangeError | Value is outside the allowed range |
| URIError | Bad use of encodeURI / decodeURI |
| EvalError | Problems using eval() (rare) |
| AggregateError | Multiple errors in a group of promises |
+----------------+----------------------------------------+JavaScript provides several constructs for error handling: try…catch, throw, and finally. Let’s explore these with simple examples.
1. The try…catch Statement.
The try…catch statement allows you to test a block of code for errors (try) and define a response (catch) if an error occurs.
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
}Example:
try {
let result = riskyOperation(); // Assume this function may throw an error
console.log(result);
} catch (error) {
console.log("An error occurred: " + error.message);
}Let me Explain,
- The try block contains code that might throw an error.W3Schools
- If an error occurs, the catch block executes, allowing you to handle the error gracefully.
2. throw in JavaScript
throw is how you create your own errors in JavaScript.
Sometimes, you want to stop your code on purpose if something goes wrong — for example, if someone enters the wrong type of data. That’s when you use throw.
Get Gaurav Davre’s stories in your inbox
Join Medium for free to get updates from this writer.
Example:
function divide(a, b) {
if (b === 0) {
throw new Error("You can't divide by zero!");
}
return a / b;
}Now if you call: divide(10, 0);JavaScript will stop and say:Uncaught Error: You can’t divide by zero!
Note: You can throw any value, but it’s best to throw an Error object so you get more helpful info like stack traces.
Examples:
throw "Something went wrong"; // not recommended
throw 42; // also not recommended
throw new Error("This is better!"); ✅3. finally Block
You can also use a finally block if you want some code to run no matter what (whether there’s an error or not):
try {
// risky code
} catch (error) {
// error handling
} finally {
// this always runs
}Summary./
> Use try to test risky code.
> Use catch to handle errors.
> throw lets you create your own errors.
> Use finally if you want to always do something (like clean up resources).
./ See you soon…









