Skip to content

Latest commit

 

History

History
42 lines (33 loc) · 1.53 KB

File metadata and controls

42 lines (33 loc) · 1.53 KB
chapter 12
pageNumber 85
description In programming errors happen for various reasons, some happen from code errors, some due to wrong input, and other unforeseeable things. The try catch helps prevent the entire script from halting or crashing when an error occurs, allowing us to gracefully handle exceptional cases and provide a fallback behavior.

try... catch

Instead of halting the code execution, we can use the try...catch construct that allows catching errors without dying the script. The try...catch construct has two main blocks; try and then catch.

try {
  // code...
} catch (err) {
  // error handling
}

At first, the code in the try block is executed. If no errors are encountered then it skips the catch block. If an error occurs then the try execution is stopped, moving the control sequence to the catch block. The cause of the error is captured in err variable.

try {
  // code...
  alert('Welcome to Learn JavaScript');  
  asdk; // error asdk variable is not defined
} catch (err) {
  console.log("Error has occurred");
}

{% hint style="warning" %} try...catch works for runtime errors meaning that the code must be runnable and synchronous. {% endhint %}

To throw a custom error, a throw statement can be used. The error object, that gets generated by errors has two main properties.

  • name: error name
  • message: details about the error

{% hint style="info" %} If we don't need an error message catch can be omitted. {% endhint %}