Day 9: Errors
Lesson 2: Catch()
The catch
block of the try/catch
structure can also take an argument that receives the thrown error. Here's the previous example expanded:
By accessing the message we can see what error was thrown, then assuming we (or more likely, another developer) used a sensible error message we can investigate and fix it.
If the error wasn't that helpful then you can get the stack
property as well to see if it can tell you where the error occurred. It won't be all that helpful here but go ahead and change the .message
to .stack
above to see where the error was thrown.
Writing good error messages is an art that takes time to develop so start practicing now when you find yourself writing error messages to help you in the future.
Something important to know is that if an error is thrown in the try
, no code after the throw
will be run in the try
block.
Heres an example
See how the Hello ...
is logged but World
isn't?
That's because after an error has happen it's assumed that nothing in the try
block after that point is safe to run, so it's skipped and we go to the catch
block to deal with the error.