> For the complete documentation index, see [llms.txt](https://js201.gitbook.io/js-101/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://js201.gitbook.io/js-101/try...-catch.md).

# Error Handling

In programming errors happen for various reasons, some happen from code errors,  some due to wrong input, and other unforeseeable things.  When an error happens, the code stops and generates an error message usually seen in the console.&#x20;

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`.&#x20;

```javascript
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.

```javascript
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.&#x20;

* **name**:  error name
* **message**: details about the error&#x20;

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