Categories
Code

Finally

We can add another block to try/catch. This is done with the “finally” keyword. What the finally code block does is run always. So even if there is an error, the finally block still runs. It runs regardless if there is an error or not. Here is the syntax…

try {
    let animal = newAnimal;
} catch(error){
    console.log(‘error: ‘, error);
} finally{
    console.log(‘this will always run’);
} 

Happy Coding!

Clay Hess

Categories
Code

Try and Catch

The try/catch keywords allow us to handle errors more gracefully. Here is an example…

try {
    let animal = newAnimal;
} catch(error){
    console.log(‘error: ‘, error);
}
console.log(‘code should continue to run…’); 

What we are doing here is telling JavaScript to “try” running the code. If there is an error catch it and do something with it. In this case, we are simply outputting it to the console, but we could log it to a server, etc. The error is caught, but the code does not stop running. If you run this code, you will see the error logged to the console and you should then see the last log statement outside the try/catch.

Happy Coding!

Clay Hess

Categories
Code

Errors

Errors happen in code. We need to be able to handle them in our JavaScript code. We also may sometimes wish to throw our own errors in specific situations. Ideally we want to handle errors gracefully to provide the best end user experience we can. Suppose we have the following code…

let animal = newAnimal;
console.log(animal); 

This code will throw a reference error because newAnimal is not defined. This will bring our code to a halt, but is that really what we want to do? We can use tools like try/catch to handle errors more efficiently.

Happy Coding!

Clay Hess