Controlling the flow of your statements can also be handled using Try, Throw and Catch in your blocks of code.

Photo by Frankie Lopez on Unsplash

In JavaScript our code is often wrapped in curly’s ({} ), these are our blocks of code. Statements such as if...else or while...for to name a few help ensure our code has a distinct flow. What happens if your function returns to you an error? Often times, JavaScript will throw you a bone and prevent your function from causing havoc. You might even be able to get a hint on where to look for your error. This is what JavaScript refers to as throwing an exception, or throwing you an error object. On how to edit your error message click here.

This is where our try...catch comes into play. For comparison think of a try...catch block as football offensive play. The goal is to try to get a touchdown or at least gain a few yards to get closer to that end goal. In this way this play is our try or attempts in our block of code. If all else fails we need to catch the ball in order to keep attacking another day. In our case the catch block will handle the case in which we fail.

Heres the layout for your try...catch blocks:

try{
//Insert what you want your code to run and attempt here
}
catch (exceptionObject) {
//What do you want to happen if the code breaks/fails
//The the error that is being 'handled' can be passed as
// an argument in your catch block
}
** HINT: if you want to see what error you are getting back best practice states to console.error(exceptionObject) within your catch block instead of using a console.log(exceptionObject)
  1. Handling database Transactions such as CRUD functionality like creating a new user in your DB.
  2. When handling asynchronous effects/events

Over all use catch to handle an exception/error when you can expect a failure. These are usually from systems or apis you are trying to access. Brownie points for knowing how to handle them, try not to leave it as a log. JavaScripts safety net is awesome! try catch gives you that extra insurance that the entire app doesn’t burst into flames.

You will eventually get to your destination if you continue to tackle it one step at a time. Find me on Twitter @NetalyCodes

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store