No matter how good your code is, errors are inevitable. What matters is how you handle them.
JavaScript provides powerful tools like try, catch, and finally to manage errors gracefullyโso your application doesnโt crash unexpectedly.
๐จ What Are Errors in JavaScript?
Errors are problems that occur during code execution (runtime).
Example:
```js id="err1"
console.log(x); // โ ReferenceError: x is not defined
### Common Types of Errors:
* **ReferenceError** โ variable not defined
* **TypeError** โ wrong type usage
* **SyntaxError** โ invalid code
---
## ๐ต The Problem Without Error Handling
```js id="err2"
function divide(a, b) {
return a / b;
}
console.log(divide(10, 0));
console.log("This may still run...");
Some errors can break your app or cause unexpected behavior.
๐ก Using try and catch
The try...catch block lets you handle errors safely.
```js id="try1"
try {
let result = riskyFunction();
console.log(result);
} catch (error) {
console.log("Something went wrong:", error.message);
}
---
### ๐ Flow
```id="viz1"
try block runs
โ
error occurs?
โ yes
catch block runs
โ
program continues safely
๐ฅ Understanding the catch Block
```js id="catch1"
try {
console.log(x);
} catch (error) {
console.log(error.name); // ReferenceError
console.log(error.message); // x is not defined
}
๐ The `error` object gives useful debugging info.
---
## ๐งน The `finally` Block
The `finally` block always runsโwhether an error occurs or not.
```js id="finally1"
try {
console.log("Trying...");
} catch (error) {
console.log("Error occurred");
} finally {
console.log("This always runs");
}
๐ Execution Order
try โ catch (if error) โ finally
๐ฅ Throwing Custom Errors
You can create your own errors using throw.
```js id="throw1"
function withdraw(balance, amount) {
if (amount > balance) {
throw new Error("Insufficient balance");
}
return balance - amount;
}
try {
withdraw(1000, 1500);
} catch (err) {
console.log(err.message);
}
---
### ๐ง Why Use Custom Errors?
* Better debugging
* Clear error messages
* Control program flow
---
## ๐ ๏ธ Real-World Example
```js id="real1"
function parseJSON(data) {
try {
return JSON.parse(data);
} catch (err) {
console.log("Invalid JSON");
return null;
}
}
โ Why Error Handling Matters
โ 1. Prevents Crashes
Your app keeps running even when something fails.
โ 2. Better User Experience
Users see meaningful messages instead of broken screens.
โ 3. Easier Debugging
You get clear insights into what went wrong.
โ 4. Graceful Failure
Instead of crashing:
```js id="bad"
app crashes โ
You handle it:
```js id="good"
show error message โ
continue execution โ
โ ๏ธ Important Notes
-
try...catchonly works for runtime errors - It does not catch syntax errors
- Works synchronously (async needs special handling like
async/await)
๐ง Best Practices
- Keep
tryblocks small - Use meaningful error messages
- Donโt ignore errors silently
- Use
finallyfor cleanup (closing resources, etc.)
๐ Final Thoughts
Error handling is not optionalโitโs essential.
Using try, catch, and finally, you can:
- Build robust applications
- Handle failures gracefully
- Improve debugging and maintenance
๐ง Quick Summary
- Errors happen at runtime
-
tryโ test code -
catchโ handle errors -
finallyโ always runs -
throwโ create custom errors
Top comments (0)