Try Throw Catch
Controlling the flow of your statements can also be handled using Try, Throw and Catch in your blocks of code.
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)
When to use Try, Catch, Throw?
- Handling database Transactions such as CRUD functionality like creating a new user in your DB.
- 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.