DEV Community

Souvik Guha Roy
Souvik Guha Roy

Posted on

Error Handling in JavaScript: Try, Catch, Finally

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...");
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ฅ 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");
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Š Execution Order

try โ†’ catch (if error) โ†’ finally
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ฅ 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;
  }
}
Enter fullscreen mode Exit fullscreen mode

โ“ 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 โœ…
Enter fullscreen mode Exit fullscreen mode

โš ๏ธ Important Notes

  • try...catch only works for runtime errors
  • It does not catch syntax errors
  • Works synchronously (async needs special handling like async/await)

๐Ÿง  Best Practices

  • Keep try blocks small
  • Use meaningful error messages
  • Donโ€™t ignore errors silently
  • Use finally for 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)