# try/catch & Custom Errors — JavaScript

Source: https://www.geekswithgeeks.com/en/javascript/js-error-handling

> Catching failures gracefully, and defining your own error types.

## try / catch / finally

Code in `try` runs first; if it throws, `catch` handles it; `finally` always runs, error or not.

```js
try {
  JSON.parse("{ invalid json");
} catch (err) {
  console.log("Failed:", err.message);
} finally {
  console.log("Always runs");
}
```

## Throwing errors

`throw` raises an error yourself, stopping normal execution until something catches it.

```js
function divide(a, b) {
  if (b === 0) throw new Error("Cannot divide by zero");
  return a / b;
}
try {
  divide(10, 0);
} catch (err) {
  console.log(err.message);  // Cannot divide by zero
}
```

## Custom error classes

Extend the built-in `Error` class to create your own, more descriptive error types.

```js
class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError";
  }
}
throw new ValidationError("Invalid input");
```

## Catch specifically

Check `err.name` or use `instanceof` to handle different error types differently instead of one generic catch-all.
