30 Days Of JavaScript

Day 20: Consolidation 3

Lesson 1: Errors


Errors are created and thrown like this:

To gracefully deal with an error you should use a try/catch.

Anything thrown in the try block with be caught by the catch block. If you don't have a catch block, the error will propagate up through your application until it finds a catch block in it's scope, or until the browser catches it and displays it in the console.

Remember that any function in your try block can throw an error, these will also be caught by your catch block if they don't have their own try/catch to handle it.


The catch block also takes an argument, generally named e, err or error (it's up to you as the developer what you want to call it, you could all it eggs but that wouldn't make much sense)

When ever an error is thrown in a try block it will stop the execution of the code in and jump to the catch. So anything after the line that throws isn't executed.


Try/Catch are two legs of the Try/Catch/Finally tripod that looks like this:

1try {
2  // try code
3} catch (error) {
4  // catch code
5} finally {
6  // finally code

try is where we run our potentially risky code.

catch is where we run and process any errors that get thrown

finally is always run regardless of if an error was thrown or not.

Finally will run no matter if the try block successfully completed or if the catch block got run by a thrown error.


Go Pro?

Upgrade to Pro for quizzes, tracked progress and a completion certificate for just $25 🚀

Want more developer tips, tricks and tools?
Then follow me:
FREE Coding Career Quick Start Guide 🚀
Discover the best way to learn to code, how to land a job and valuable resources to help your journey in this free 15 page value packed guide.
Looking to email me? You can get me on my first name at allthecode.co