30 Days Of JavaScript

Day 20: Consolidation 3

Lesson 1: Errors

Throw

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.

Catch

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.

Finally

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
7}

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.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co