Error handling with try-catch

Posted on

With try and catch, we can react to errors that could happen in our code. We can recover from those errors by following a different code path or doing cleanup. If the function does not throw an error, the execution skips the catch-block.

// `try` to do something that could fail
try {
  // this may or may not be possible
  makeItBeFriday()
 
  // if we get here, the function worked
  console.log("It is Friday now!")
} catch (error) {
  // if something in `try` fails and throws an error, we end up here
  console.log("Sorry, it is not Friday now.")
}
// `try` to do something that could fail
try {
  // this may or may not be possible
  makeItBeFriday()
 
  // if we get here, the function worked
  console.log("It is Friday now!")
} catch (error) {
  // if something in `try` fails and throws an error, we end up here
  console.log("Sorry, it is not Friday now.")
}
Debug
none
Grid overlay