Try and Catch Errors

Hello,

I’m finding it hard to understand the try and catch errors. Please see below -

try {
let name = function() {
let myname = “Ejovi”;
return console.log('Hello ’ + mynam);
}
} catch (e) {
console.log(‘Really’)
}

I expect the code in the try block to return a reference error which will inturn make the code in the catch error execute. But then there is nothing in the console at all.

That is complete function that never gets called. Perhaps place the try-catch inside that function body and then call it. In this case there won’t be any error.

The general idea is that when we cannot be certain there won’t be an error (without some form of validation, first) we write the code inside the TRY block. If there are no errors, the code executes fine. If an error is encountered, it channels over to CATCH.

const lower = function (a) {
  try {
    return a.toLowerCase()
  }
  catch (e) {
    throw e;
  }
}
console.log(lower('FIVE'))    //  five
console.log(lower(5))
// TypeError: a.toLowerCase is not a function

We don’t have to throw an error, though. We can write a different return statement, or log our own error message.

1 Like