DEV Community

gagecantrelle
gagecantrelle

Posted on

The Basics of Try/Catch

Have you ever run into a problem when coding and just can’t find where that error is coming from? This error could be anything from a typo, missing line of code, or undefined data. Thanks to that error it could also stop your console.log from running, making it harder to see what some variables equal to, or where the error is coming from. Luckily, there is a code statement you can use to help avoid having that problem Try/Catch. Similar to the .Then and .Catch methods used in promise. If there is an error in the Try block the Catch block will catch it and then run the code in the Catch block. Even though .Then/.Catch and Try/Catch are similar, Try/Catch are statements that can be used anywhere while .then/.catch are methods that can only be used in asynchronous code. Here is a blog I wrote for promises that use .then and .catch methods in its code https://dev.to/gagecantrelle/the-basic-of-promises-amf

Try/Catch history

During the early days of JavaScript when it was still somewhat new to the world, the developers were adding error-checking methods to it. By 1999 for javaScript version 1.4 the Try/Catch statement was added. It Was commonly used in code to check if it was running properly or not. Then at a later point in time, the Finally statement was added to the Try/Catch method. It works similarly to promises and is set similarly to an if statement. Making it easy to understand how it works and set up.

How the Try, Catch, Finally statements work

  1. Try/Catch works best when working with data fetch from another server or asynchronous code, since you never know what you might get back. For the Try code block to work you must have a Catch or Finally code block at the end of Try. It does not take in any parameters or conditions. If a line of code in the Try block runs into an error it will stop running the rest of the code in that block, This will also happen if a variable is set to undined in the block. The Catch statement will take in an error parameter with an error argument, related to the error from the Try block. Catch can even work if not given any parameter, this will not affect how it will run.
const {url} = request(./urlExmple.js)
let data = fetch(url)
//"{num: 2}"
try{
let editData = JSON.parse(data);
let str = 1 + editData.num;
//the console should log a string of 3
console.log(str);
}catch (error){
console.log(error);
console.log('error on line 11');
};
//result will be '3'
Enter fullscreen mode Exit fullscreen mode
  1. The Finally statement can be added to the end of the Catch method or can replace the Catch method, It will always run if there is an error or not. The order in which Finally is used dose not affect the code

try {
  let str = 1 + 2 + '';
  console.log(str);
} catch (error){
  console.log(error);
  console.log('error on line 6');
} finally {
  //will run after Catch even if there is an error or not
  console.log('hey your Try block on line 1 has run')
}
//result will be '3' and 'hey your Try method on line 1 has run'
Enter fullscreen mode Exit fullscreen mode

Try/Catch examples

Import { highOrderAsyncFunction } from './HOF.js;
Import { data } from './examples.js' 

let result = null;

Try{
result = highOrderAsyncFunction(data).map();
for(let i = 0; i < result.length; i++){
let test = result[i].val
console.log(test)
}
}catch{
console.log('Error: the high order function on line 7 in HOFTEST.js, data given is not the correct data type')
result = ['default’];
}
Enter fullscreen mode Exit fullscreen mode

Let's say you have a high-order function that is also asynchronous, There are times when you might run into an error.
this error could be anything from a type error to a value being
undefined. Normally with Asynchronous code it usually the value
being undefined, sometimes it's an array or object with undefined values. Since the Try statement will throw an error if something
returns undefined or sets a variable to undefined value. you can use it to make sure that the code doesn't return any undefined
values.

function getData (url){
  return fetch(url)
     .then((data)=>{
        try{
          let changeData = parse.JSON(data)

          return changeData.images[3]  

        }catch(error){
          console.log(error)
        }

     }
}
Enter fullscreen mode Exit fullscreen mode

Another good use for try/catch is in promises. Let's say you used the fetch method to send a request and you receive the data from the server. Although there are no errors here, There is a chance that there is something wrong with the requested data or not. You can use try/catch to check if the data requested is fulfilled or rejected because of an error.

Top comments (0)