DEV Community

Nic
Nic

Posted on

JavaScript try...catch

Try catch confused me for a long time, both how you use it and why you use it. Let's start with how.

It's like if else, but not

If you were to write try catch as an if else, it would look like this:

if(it works) {
  do something
} else {
  show an error
}
Enter fullscreen mode Exit fullscreen mode

But it's not an if else, so it actually looks like this:

try {
  getting it to work
  it worked, so do something
} catch {
  show an error
}
Enter fullscreen mode Exit fullscreen mode

It's the same, but the condition is effectively inside the try block. And not an explicit condition. And involves magic. Or so it seems. Because if the thing doesn't work it skips everything else in the try block and skips to the catch block.

It's the difference to if else that trips me up, even though the try and catch are good words to understand what's going on. For example:

try {
  to fly on a trapeze
  fly!
} catch {
  in the net
}
Enter fullscreen mode Exit fullscreen mode

So in summary, it's an if else, but the condition is implicit.

But what's it for?

A good use is for APIs. If the API doesn't send back data then it's good to find a way to tell the user that, rather than leaving them waiting, wondering if the data is ever going to arrive.

try {
  to get some data from an API
  show data
} catch (error) {
  show error
}
Enter fullscreen mode Exit fullscreen mode

I added a bit here which I skipped from my explanation further up, for the sake of simplicity. The cool thing that try catch does is that when it fails, it sends that information to the catch block. So your error might be "404 Not found" for example.

There's another extra bit you can add, which is finally. It runs whether you succeeded or not, after it's finished either the try or the catch block:

try {
  to fly on a trapeze
  fly!
} catch (me) {
  me in the net
} finally {
  have another go!
}
Enter fullscreen mode Exit fullscreen mode

It's simple when you know how it works!

Oldest comments (1)

Collapse
 
ajaymarathe profile image
Ajay Marathe

Nice and helpful