# Try...catch and Throw

# Try...catch

When you want to run some code and you are not sure if it will work because of lack of support, or you know that sometimes a value or Object will be missing, then you can use a try...catch block.

There are two parts. The first is the try block. It is where you put all the code that you want to attempt.

The second is the catch block. It will only run if the code in the try block fails. It will be passed an Error object with the details of the problem.

try {
  let str = "hello";
  let result = str.convertToPolish();
  // this function does not exist
  console.log(result); //this line will never run.
} catch (err) {
  //the variable err holds the error object
  console.error(err.message, err.code);
}
1
2
3
4
5
6
7
8
9

In this example, we try to call a string method that does not exist. So, an Error is generated and passed to the catch block.

# Throw and new Error()

If you ever want to create your own custom Error, we can do that with the new Error() constructor. That will give you an Error object. You can put throw in front of the new Error(). If you do this inside a try block then it will be passed to the catch block.

try {
  let e = new Error("My custom error");
  throw e;
  //these two lines could be combined too
  // throw new Error('My custom error');
} catch (err) {
  console.error(err.message); //"My custom error"
}
1
2
3
4
5
6
7
8

Back to Week 4 main page

Last Updated: 6/13/2020, 11:30:19 PM