Skip to main content

Command Palette

Search for a command to run...

Error Handling in JavaScript: Try, Catch, Finally

Published
3 min read
Error Handling in JavaScript: Try, Catch, Finally

When we write JavaScript, we expect things to work.

But in real world apps, things break.

Maybe:

  • API fails

  • variable is undefined

  • wrong data comes

And when something breaks, JavaScript throws an error and stops execution.

That’s not good for users.

So we need a way to handle errors properly.

In this blog I will share how I understand error handling using try, catch and finally.


What errors are in JavaScript

Errors are situations where something goes wrong during execution.

Example:

console.log(x)

Output:

ReferenceError: x is not defined

Here:

JavaScript stops execution

So if this happens in real app, user experience breaks.


Why error handling matters

Instead of crashing the app, we can handle the error and continue.

show message, log error, fallback behavior

So error handling is about:

graceful failure


Using try and catch

Basic idea:

try the code if error happens → catch it

Example:

try {
  console.log(x)
} catch (error) {
  console.log("Something went wrong")
}

Now:

instead of crash → we handle it


How it actually flows


Accessing the error

try {
  console.log(x)
} catch (error) {
  console.log(error.message)
}

error contains details

Useful for debugging.


The finally block

Finally always runs.

No matter what.

Example:

try {
  console.log("Try running")
} catch (err) {
  console.log("Error")
} finally {
  console.log("Always runs")
}

Output:

Try running
Always runs

Even if error happens:

finally still runs


Why finally is useful

Use it for:

  • cleanup

  • closing resources

  • final steps


Try → Catch → Finally flow


Throwing custom errors

Sometimes we want to create our own error.

function checkAge(age) {
  if (age < 18) {
    throw new Error("Age must be 18+")
  }

  console.log("Access granted")
}

try {
  checkAge(16)
} catch (err) {
  console.log(err.message)
}

Here:

we manually throw error


Why throw is useful

  • validate data

  • enforce rules

  • control flow


Real world feel

Instead of app crashing:

we control what happens when something goes wrong


Common pattern

try {
  // risky code
} catch (err) {
  // handle error
} finally {
  // always run
}

Important thing to remember

  • try only catches runtime errors

  • syntax errors won’t be caught


Errors will happen.

That’s normal.

What matters is how you handle them.

Using try, catch, and finally helps you:

prevent crashes

debug better

build stable apps

Error Handling in JavaScript: Try, Catch, Finally